1, Introduction to WLAN
- Wireless Local Area Networks (WLAN) is a LAN that sends and receives data through radio, infrared optical signals or other technologies. Users can realize network communication without physical connection between nodes through WLAN. It is often used in the office and public environment where users carry mobile terminals.
- HarmonyOS WLAN service system provides users with WLAN basic functions, P2P (peer-to-peer) functions and corresponding services of WLAN message notification, so that applications can be interconnected with other devices through WLAN.
- This development guide provides guidance for multiple development scenarios, involving the call of multiple API interfaces. Before calling the API, the application needs to apply for the corresponding access permission.
2, WLAN basic functions
① Application scenario
- Get WLAN status and query whether WLAN is on.
- Initiate a scan and obtain the scan results.
- Obtain connection status details, including connection information, IP information, etc.
- Get the device country code.
- Gets whether the device supports the specified capability.
② API description
- The basic functions of WLAN are provided by WiFi device, and its interface description is as follows:
Interface name | describe | Required permissions |
---|
getInstance(Context context) | Get the WLAN function management object instance, and call the WLAN basic function API through this instance | NA |
---|
isWifiActive() | Get the current WLAN on state | ohos.permission.GET_WIFI_INFO |
---|
scan() | Initiate WLAN scan | ohos.permission.SET_WIFI_INFO ohos.permission.LOCATION |
---|
getScanInfoList() | Get last scan results | ohos.permission.GET_WIFI_INFO ohos.permission.LOCATION |
---|
isConnected() | Get current WLAN connection status | ohos.permission.GET_WIFI_INFO |
---|
getLinkedInfo() | Get current WLAN connection information | ohos.permission.GET_WIFI_INFO |
---|
getIpInfo() | Get the WLAN IP information of the current connection | ohos.permission.GET_WIFI_INFO |
---|
getSignalLevel(int rssi, int band) | The number of signal cells is calculated by RSSI and frequency band | NA |
---|
getCountryCode() | Get the country code of the device | ohos.permission.LOCATION ohos.permission.GET_WIFI_INFO |
---|
isFeatureSupported(long featureId) | Gets whether the device supports the specified attribute | ohos.permission.GET_WIFI_INFO |
---|
③ Get WLAN status
- Call the getInstance (context) interface of WiFi device to obtain the WiFi device instance, which is used to manage the local WLAN operation.
- Call isWifiActive() interface to query whether WLAN is turned on.
// Get WLAN management object
WifiDevice wifiDevice = WifiDevice.getInstance(context);
// Call the interface to get WLAN switch status
boolean isWifiActive = wifiDevice.isWifiActive(); // If WLAN is turned on, it returns true; otherwise, it returns false
④ Initiate scan and get results
- Call the getInstance (context) interface of WiFi device to obtain the WiFi device instance, which is used to manage local WLAN operations.
- Call the scan () interface to initiate a scan.
- Call the getscaninflist() interface to get the scan results.
// Get WLAN management object
WifiDevice wifiDevice = WifiDevice.getInstance(context);
// Call WLAN scan interface
boolean isScanSuccess = wifiDevice.scan();
// Call to get scan results
List<WifiScanInfo> scanInfos = wifiDevice.getScanInfoList();
⑤ Get connection status details
- Call the getInstance (context) interface of WiFi device to obtain the WiFi device instance, which is used to manage local WLAN operations.
- Call isConnected() interface to get the current connection status.
- Call the getLinkedInfo() interface to get the connection information.
- Call getIpInfo() interface to get IP information.
// Get WLAN management object
WifiDevice wifiDevice = WifiDevice.getInstance(context);
// Call the WLAN connection status interface to determine whether the current device is connected to WLAN
boolean isConnected = wifiDevice.isConnected();
if (isConnected) {
// Get WLAN connection information
Optional<WifiLinkedInfo> linkedInfo = wifiDevice.getLinkedInfo();
// Get SSID in connection information
String ssid = linkedInfo.get().getSsid();
// Get IP information of WLAN
Optional<IpInfo> ipInfo = wifiDevice.getIpInfo();
// Obtain the IP address and gateway in the IP information
int ipAddress = ipInfo.get().getIpAddress();
int gateway = ipInfo.get().getGateway();
}
⑥ Get device country code
- Call the getInstance (context) interface of WiFi device to obtain the WiFi device instance, which is used to manage local WLAN operations.
- Call the getCountryCode () interface to obtain the country code of the device.
// Get WLAN management object
WifiDevice wifiDevice = WifiDevice.getInstance(context);
// Get the country code of the current device
String countryCode = wifiDevice.getCountryCode();
⑦ Determine whether the device supports the specified capability
- Call the getInstance (context) interface of WiFi device to obtain the WiFi device instance, which is used to manage local WLAN operations.
- Call the isFeatureSupported (long featureId) interface to determine whether the device supports the specified capability.
// Get WLAN management object
WifiDevice wifiDevice = WifiDevice.getInstance(context);
// Gets whether the current device supports the specified capability
boolean isSupportInfra = wifiDevice.isFeatureSupported(WifiUtils.WIFI_FEATURE_INFRA);
isSupportInfra5g = wifiDevice.isFeatureSupported(WifiUtils.WIFI_FEATURE_INFRA_5G);
isSupportPasspoint = wifiDevice.isFeatureSupported(WifiUtils.WIFI_FEATURE_PASSPOINT);
isSupportP2p = wifiDevice.isFeatureSupported(WifiUtils.WIFI_FEATURE_P2P);
isSupportHotspot = wifiDevice.isFeatureSupported(WifiUtils.WIFI_FEATURE_MOBILE_HOTSPOT);
isSupportAware = wifiDevice.isFeatureSupported(WifiUtils.WIFI_FEATURE_AWARE);
isSupportApSta = wifiDevice.isFeatureSupported(WifiUtils.WIFI_FEATURE_AP_STA);
isSupportWpa3Sae = wifiDevice.isFeatureSupported(WifiUtils.WIFI_FEATURE_WPA3_SAE);
isSupportWpa3SuiteB = wifiDevice.isFeatureSupported(WifiUtils.WIFI_FEATURE_WPA3_SUITE_B);
isSupportOwe = wifiDevice.isFeatureSupported(WifiUtils.WIFI_FEATURE_OWE);
3, Untrusted hotspot configuration
① Application scenario
- The application can add a specified hotspot, and its network selection priority is lower than the saved hotspot. If the hot spot is judged to be the most appropriate hot spot after scanning, the hot spot is automatically connected.
- Applications or other modules can complete the following functions through interfaces:
-
- Set the third-party hotspot configuration.
-
- Delete third-party hotspot configuration.
② API description
- WiFi device provides the untrusted hotspot configuration function of WLAN, and its interface description is as follows:
Interface name | describe | Required permissions |
---|
getInstance(Context context) | Get the WLAN function management object instance, and call the API of untrusted hotspot configuration through this instance | NA |
---|
addUntrustedConfig(WifiDeviceConfig config) | Add untrusted hotspot configuration. The network selection priority is lower than the saved hotspot | ohos.permission.SET_WIFI_INFO |
---|
removeUntrustedConfig(WifiDeviceConfig config) | Delete untrusted hotspot configuration | ohos.permission.SET_WIFI_INFO |
---|
③ Add untrusted hotspot configuration
- Call the getInstance (context) interface of WiFi device to obtain the WiFi device instance, which is used to manage local WLAN operations.
- Call the adduntrustedconfig (WiFi deviceconfig) interface to set the untrusted configuration added by the three parties.
// Get WLAN management object
WifiDevice wifiDevice = WifiDevice.getInstance(context);
// Set the untrusted configuration added by the third party
WifiDeviceConfig config = new WifiDeviceConfig();
config.setSsid("untrusted-exist");
config.setPreSharedKey("123456789");
config.setHiddenSsid(false);
config.setSecurityType(WifiSecurity.PSK);
boolean isSuccess = wifiDevice.addUntrustedConfig(config);
④ Delete untrusted hotspot configuration
- Call the getInstance (context) interface of WiFi device to obtain the WiFi device instance, which is used to manage the local WLAN operation.
- Call the removeuntrustedconfig (WiFi deviceconfig) interface to delete the untrusted configuration added by the third party.
// Get WLAN management object
WifiDevice wifiDevice = WifiDevice.getInstance(context);
// Set and delete the untrusted configuration added by the third party
WifiDeviceConfig config = new WifiDeviceConfig();
config.setSsid("untrusted-exist");
config.setPreSharedKey("123456789");
config.setHiddenSsid(false);
config.setSecurityType(WifiSecurity.PSK);
boolean isSuccess = wifiDevice.removeUntrustedConfig(config);
4, P2P function
① Application scenario
- WLAN P2P function is used for peer-to-peer data transmission between devices.
- The application can complete the following functions through the interface:
-
-
- Create and remove groups.
-
- Initiate a connection to the peer device.
-
- Get P2P related information.
② API description
- WiFi p2pcontroller provides WLAN P2P function. The interface description is as follows:
Interface name | describe | Required permissions |
---|
init(EventRunner eventRunner, WifiP2pCallback callback) | Initialize the messenger of P2P. If and only if the messenger is successfully initialized, other functions of P2P can be used normally | ohos.permission.GET_WIFI_INFO ohos.permission.SET_WIFI_INFO |
---|
discoverDevices(WifiP2pCallback callback) | Search for available P2P devices nearby | ohos.permission.GET_WIFI_INFO |
---|
stopDeviceDiscovery(WifiP2pCallback callback) | Stop searching for nearby P2P devices | ohos.permission.GET_WIFI_INFO |
---|
createGroup(WifiP2pConfig wifiP2pConfig, WifiP2pCallback callback) | Establish P2P group | ohos.permission.GET_WIFI_INFO |
---|
removeGroup(WifiP2pCallback callback) | Remove P2P group | ohos.permission.GET_WIFI_INFO |
---|
requestP2pInfo(int requestType, WifiP2pCallback callback) | Request P2P related information, such as group information, connection information, device information, etc | ohos.permission.GET_WIFI_INFO |
---|
connect(WifiP2pConfig wifiP2pConfig, WifiP2pCallback callback) | Initiate a connection to the specified device | ohos.permission.GET_WIFI_INFO |
---|
cancelConnect(WifiP2pCallback callback) | Cancels the connection initiated to the specified device | ohos.permission.GET_WIFI_INFO |
---|
③ Start and stop P2P search
- Call the getInstance (Context context) interface of WifiP2pController to obtain the P2P controller instance for managing P2P operations.
- Call init (eventrunner, eventrunner, WiFi 2pcallback) to initialize the P2P controller instance.
- Initiate P2P search.
- Get P2P search callback information.
- Stop P2P search.
try {
// Get P2P management object
WifiP2pController wifiP2pController = WifiP2pController.getInstance(this);
// Initialize the P2P management object, which is used to establish P2P messenger and other behaviors
wifiP2pController.init(EventRunner.create(true), null);
// Create P2P callback object
P2pDiscoverCallBack p2pDiscoverCallBack = new P2pDiscoverCallBack();
// Initiate P2P search
wifiP2pController.discoverDevices(p2pDiscoverCallBack);
// Stop P2P search
wifiP2pController.stopDeviceDiscovery(p2pDiscoverCallBack);
} catch (RemoteException re) {
HiLog.error(LABEL, "exception happened.");
}
// Get the callback information of P2P start and stop search (failure or success)
private class P2pDiscoverCallBack extends WifiP2pCallback {
@Override
public void eventExecFail(int reason) {
HiLog.warn(LABEL, "discoverDevices eventExecFail reason : %{public}d", reason);
}
@Override
public void eventExecOk() {
HiLog.info(LABEL, "discoverDevices eventExecOk");
}
}
④ Creating and removing groups
- Call the getInstance (Context context) interface of WifiP2pController to obtain the P2P controller instance for managing P2P operations.
- Call init (eventrunner, eventrunner, WiFi 2pcallback) to initialize the P2P controller instance.
- Create a P2P group.
- Remove the P2P group.
try {
// Get P2P management object
WifiP2pController wifiP2pController = WifiP2pController.getInstance(this);
// Initialize the P2P management object, which is used to establish P2P messenger and other behaviors
wifiP2pController.init(EventRunner.create(true), null);
// Create the configuration required for P2P group building
WifiP2pConfig wifiP2pConfig = new WifiP2pConfig("DEFAULT_GROUP_NAME", "DEFAULT_PASSPHRASE");
wifiP2pConfig.setDeviceAddress("02:02:02:02:03:04");
wifiP2pConfig.setGroupOwnerBand(0);
// Create P2P callback object
P2pCreateGroupCallBack p2pCreateGroupCallBack = new P2pCreateGroupCallBack();
// Create P2P group
wifiP2pController.createGroup(wifiP2pConfig, p2pCreateGroupCallBack);
// Remove P2P group
wifiP2pController.removeGroup(p2pCreateGroupCallBack);
} catch (RemoteException re) {
HiLog.error(LABEL, "exception happened.");
}
private class P2pCreateGroupCallBack extends WifiP2pCallback {
@Override
public void eventExecFail(int reason) {
HiLog.warn(LABEL, "CreateGroup eventExecFail reason : %{public}d", reason);
}
@Override
public void eventExecOk() {
HiLog.info(LABEL, "CreateGroup eventExecOk");
}
}
⑤ Initiate P2P connection
- Call the getInstance (Context context) interface of WifiP2pController to obtain the P2P controller instance for managing P2P operations.
- Call init (eventrunner, eventrunner, WiFi 2pcallback) to initialize the P2P controller instance.
- Call requestP2pInfo() to query the available P2P device information.
- Select the target device from the available device information according to different scenarios.
- Call the connect interface to initiate a connection.
try {
// Get P2P management object
WifiP2pController wifiP2pController = WifiP2pController.getInstance(this);
// Initialize the P2P management object, which is used to establish P2P messenger and other behaviors
wifiP2pController.init(EventRunner.create(true), null);
// Query the available P2P device information and obtain the P2P device information through callback
P2pRequestPeersCallBack p2pRequestPeersCallBack = new P2pRequestPeersCallBack();
wifiP2pController.requestP2pInfo(WifiP2pController.DEVICE_LIST_REQUEST, p2pRequestPeersCallBack);
} catch (RemoteException re) {
HiLog.error(LABEL, "exception happened.");
}
private class P2pRequestPeersCallBack extends WifiP2pCallback {
@Override
public void eventP2pDevicesList(List<WifiP2pDevice> devices) {
HiLog.info(LABEL, "eventP2pDevicesList when start connect group");
// Select different devices to connect according to different scenarios, and search the specified device through the MAC address
WifiP2pConfig wifiP2pConfig = getSameP2pConfigFromDevices(devices);
try {
if (wifiP2pConfig != null) {
// Initiate a connection to the specified device
wifiP2pController.connect(wifiP2pConfig, null);
}
} catch (RemoteException re) {
HiLog.error(LABEL, "exception happened in connect.");
}
}
}
private WifiP2pConfig getSameP2pConfigFromDevices(List<WifiP2pDevice> devices) {
if (devices == null || devices.isEmpty()) {
return null;
}
for (int i = 0; i < devices.size(); i++) {
WifiP2pDevice p2pDevice = devices.get(i);
HiLog.info(LABEL, "p2pDevice.getDeviceAddress() : %{private}s", p2pDevice.getDeviceAddress());
if (p2pDevice.getDeviceAddress() != null
&& p2pDevice.getDeviceAddress().equals(TARGET_P2P_MAC_ADDRESS)) {
HiLog.info(LABEL, "received same mac address");
WifiP2pConfig wifiP2pConfig = new WifiP2pConfig("DEFAULT_GROUP_NAME", "DEFAULT_PASSPHRASE"); // Configure the name and password according to the actual situation
wifiP2pConfig.setDeviceAddress(p2pDevice.getDeviceAddress());
return wifiP2pConfig;
}
}
return null;
}
⑥ Request P2P related information
- Call the getInstance () interface of WifiP2pController to obtain the P2P controller instance for managing P2P operations.
- Call init() to initialize the P2P controller instance.
- Call requestP2pInfo() to query P2P group information.
- Call requestP2pInfo() to query P2P device information.
- According to different scenarios, you can call requestP2pInfo to obtain the required information.
try {
// Get P2P management object
WifiP2pController wifiP2pController = WifiP2pController.getInstance(this);
// Initialize the P2P management object, which is used to establish P2P messenger and other behaviors
wifiP2pController.init(EventRunner.create(true), null);
// Query the available P2P group information and obtain the P2P group information through callback
P2pRequestGroupInfoCallBack p2pRequestGroupInfoCallBack = new P2pRequestGroupInfoCallBack();
wifiP2pController.requestP2pInfo(WifiP2pController.GROUP_INFO_REQUEST, p2pRequestGroupInfoCallBack);
// Query the available P2P device information and obtain the P2P device information through callback
P2pRequestDeviceInfoCallBack p2pRequestDeviceInfoCallBack = new P2pRequestDeviceInfoCallBack();
wifiP2pController.requestP2pInfo(WifiP2pController.DEVICE_INFO_REQUEST, p2pRequestDeviceInfoCallBack);
// By calling the requestP2pInfo interface, you can query the following key information
wifiP2pController.requestP2pInfo(WifiP2pController.NETWORK_INFO_REQUEST, callback); // network information
wifiP2pController.requestP2pInfo(WifiP2pController.DEVICE_LIST_REQUEST, callback); // Device list information
} catch (RemoteException re) {
HiLog.error(LABEL, "exception happened.");
}
// Group information callback
private class P2pRequestGroupInfoCallBack extends WifiP2pCallback {
@Override
public void eventP2pGroup(WifiP2pGroup group) {
HiLog.info(LABEL, "P2pRequestGroupInfoCallBack eventP2pGroup");
doSthFor(group);
}
}
// Device information callback
private class P2pRequestDeviceInfoCallBack extends WifiP2pCallback {
@Override
public void eventP2pDevice(WifiP2pDevice p2pDevice) {
HiLog.info(LABEL, "P2pRequestDeviceInfoCallBack eventP2pDevice");
doSthFor(p2pDevice);
}
}
5, WLAN message notification
① Application scenario
- WLAN message Notification is a cross process communication mechanism within HarmonyOS or with applications. After registering the message Notification, once the qualified message is sent, the registrant can receive the message and obtain the information attached to the message.
② API description
- Introduction to relevant broadcasting of WLAN message notification:
describe | Notification name | Additional parameters |
---|
WLAN status | usual.event.wifi.POWER_STATE | active_state |
---|
WLAN scan | usual.event.wifi.SCAN_FINISHED | scan_state |
---|
WLAN RSSI change | usual.event.wifi.RSSI_VALUE | rssi_value |
---|
WLAN connection status | usual.event.wifi.CONN_STATE | conn_state |
---|
Hotspot status | usual.event.wifi.HOTSPOT_STATE | hotspot_active_state |
---|
Hotspot connection status | usual.event.wifi.WIFI_HS_STA_JOIN usual.event.wifi.WIFI_HS_STA_LEAVE | - |
---|
P2P status | usual.event.wifi.p2p.STATE_CHANGE | p2p_state |
---|
P2P connection status | usual.event.wifi.p2p.CONN_STATE_CHANGE | linked_info net_info group_info |
---|
P2P device list changes | usual.event.wifi.p2p.DEVICES_CHANGE | - |
---|
P2P search state change | usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE | peers_discovery |
---|
Current P2P device changes | usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE | p2p_device |
---|
③ Development steps
- Build the message notification recipient WiFi event subscriber.
- Register WLAN change messages.
- WiFi event subscriber receives and processes WLAN broadcast messages.
// Build message receiver / Registrar
class WifiEventSubscriber extends CommonEventSubscriber {
WifiEventSubscriber(CommonEventSubscribeInfo info) {
super(info);
}
@Override
public void onReceiveEvent(CommonEventData commonEventData) {
if (commonEventData == null || commonEventData.getIntent() == null) {
return;
}
if (WifiEvents.EVENT_ACTIVE_STATE.equals(commonEventData.getIntent().getAction())) {
// Get attached parameters
IntentParams params = commonEventData.getIntent().getParams();
if (params == null) {
return;
}
int wifiState= (int) params.getParam(WifiEvents.PARAM_ACTIVE_STATE);
if (wifiState== WifiEvents.STATE_ACTIVE) { // Process WLAN open message
HiLog.info(LABEL, "Receive WifiEvents.STATE_ACTIVE %{public}d", wifiState);
} else if (wifiState == WifiEvents.STATE_INACTIVE) { // Process WLAN shutdown message
HiLog.info(LABEL, "Receive WifiEvents.STATE_INACTIVE %{public}d", wifiState);
} else { // Handling WLAN exception status
HiLog.warn(LABEL,"Unknown wifi state");
}
}
}
}
// Registration message
MatchingSkills match = new MatchingSkills();
// Add getting WLAN status change message
match.addEvent(WifiEvents.EVENT_ACTIVE_STATE);
CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(match);
subscribeInfo.setPriority(100);
WifiEventSubscriber subscriber = new WifiEventSubscriber(subscribeInfo);
try {
CommonEventManager.subscribeCommonEvent(subscriber);
} catch (RemoteException e) {
HiLog.warn(LABEL, "subscribe in wifi events failed!");
}