harmony 鸿蒙@ohos.wifiManager (WLAN)

2022-12-22 浏览 (962)

@ohos.wifiManager (WLAN)

The WLAN module provides basic wireless local area network (WLAN) functions, peer-to-peer (P2P) functions, and WLAN message notification services. It allows applications to communicate with devices over WLAN.

NOTE

The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Modules to Import

import wifiManager from '@ohos.wifiManager';

wifiManager.enableWifi9+

enableWifi(): void

Enables WLAN. This API is an asynchronous interface. The wifiStateChange callback must be registered and listened for.

System API: This is a system API.

Required permissions: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications)

System capability: SystemCapability.Communication.WiFi.STA

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.
2501003Failed to enable Wi-Fi.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		wifiManager.enableWifi();
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.disableWifi9+

disableWifi(): void

Disables WLAN. This API is an asynchronous interface. The wifiStateChange callback must be registered and listened for.

System API: This is a system API.

Required permissions: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications)

System capability: SystemCapability.Communication.WiFi.STA

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.
2501004Failed to disable Wi-Fi.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		wifiManager.disableWifi();
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.isWifiActive9+

isWifiActive(): boolean

Checks whether WLAN is enabled.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Return value

TypeDescription
booleanReturns true if WLAN is enabled; returns false otherwise.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let isWifiActive = wifiManager.isWifiActive();
		console.info("isWifiActive:" + isWifiActive);
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.scan9+

scan(): void

Starts a scan for WLAN.

Required permissions:

API version 9: ohos.permission.SET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION

API version 10 and later: ohos.permission.SET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		wifiManager.scan();
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.startScan10+

startScan(): void

System API: This is a system API.

Starts a scan for WLAN.

Required permissions: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION

System capability: SystemCapability.Communication.WiFi.STA

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		wifiManager.startScan();
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.getScanResults9+

getScanResults(): Promise<Array<WifiScanInfo>>

Obtains the scan result. This API uses a promise to return the result.

Required permissions: ohos.permission.GET_WIFI_INFO and (ohos.permission.GET_WIFI_PEERS_MAC or (ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION))

System capability: SystemCapability.Communication.WiFi.STA

Return value

TypeDescription
Promise< Array<WifiScanInfo> >Promise used to return the hotspots detected.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

wifiManager.getScanResults9+

getScanResults(callback: AsyncCallback<Array<WifiScanInfo>>): void

Obtains the scan result. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.GET_WIFI_INFO and (ohos.permission.GET_WIFI_PEERS_MAC or (ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION))

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback< Array<WifiScanInfo>>YesCallback invoked to return the result. If the operation is successful, err is 0 and data is the detected hotspots. Otherwise, err is a non-zero value and data is empty.
Array<WifiScanInfo>Hotspots detected.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

  import wifiManager from '@ohos.wifiManager';
  
  wifiManager.getScanResults((err, result) => {
      if (err) {
          console.error("get scan info error");
          return;
      }
  
      let len = result.length;
      console.log("wifi received scan info: " + len);
      for (let i = 0; i < len; ++i) {
          console.info("ssid: " + result[i].ssid);
          console.info("bssid: " + result[i].bssid);
          console.info("capabilities: " + result[i].capabilities);
          console.info("securityType: " + result[i].securityType);
          console.info("rssi: " + result[i].rssi);
          console.info("band: " + result[i].band);
          console.info("frequency: " + result[i].frequency);
          console.info("channelWidth: " + result[i].channelWidth);
          console.info("timestamp: " + result[i].timestamp);
      }
  });
  
  wifiManager.getScanResults().then(result => {
      let len = result.length;
      console.log("wifi received scan info: " + len);
      for (let i = 0; i < len; ++i) {
          console.info("ssid: " + result[i].ssid);
          console.info("bssid: " + result[i].bssid);
          console.info("capabilities: " + result[i].capabilities);
          console.info("securityType: " + result[i].securityType);
          console.info("rssi: " + result[i].rssi);
          console.info("band: " + result[i].band);
          console.info("frequency: " + result[i].frequency);
          console.info("channelWidth: " + result[i].channelWidth);
          console.info("timestamp: " + result[i].timestamp);
      }
  });

wifiManager.getScanResultsSync9+

getScanResultsSync():  Array<WifiScanInfo>

Obtains the scan result. This API returns the result synchronously.

Required permissions: ohos.permission.GET_WIFI_INFO and (ohos.permission.GET_WIFI_PEERS_MAC or (ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION))

System capability: SystemCapability.Communication.WiFi.STA

Return value

TypeDescription
 Array<WifiScanInfo>Scan result obtained.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let scanInfoList = wifiManager.getScanResultsSync();
		console.info("scanInfoList:" + JSON.stringify(scanInfoList));
		let len = scanInfoList.length;
        console.log("wifi received scan info: " + len);
		if(len > 0){
			for (let i = 0; i < len; ++i) {
				console.info("ssid: " + scanInfoList[i].ssid);
				console.info("bssid: " + scanInfoList[i].bssid);
				console.info("capabilities: " + scanInfoList[i].capabilities);
				console.info("securityType: " + scanInfoList[i].securityType);
				console.info("rssi: " + scanInfoList[i].rssi);
				console.info("band: " + scanInfoList[i].band);
				console.info("frequency: " + scanInfoList[i].frequency);
				console.info("channelWidth: " + scanInfoList[i].channelWidth);
				console.info("timestamp: " + scanInfoList[i].timestamp);
			}
		}	
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}
	

wifiManager.getScanInfoList10+

getScanInfoList(): Array<WifiScanInfo>;

Obtains the scanning result.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Return value

TypeDescription
Array<WifiScanInfo>Hotspots detected. If the application has the ohos.permission.GET_WIFI_PEERS_MAC permission, bssid in the return value is a real device address; otherwise, bssid is a random device address.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let scanInfoList = wifiManager.getScanInfoList();
		console.info("scanInfoList:" + JSON.stringify(scanInfoList));
		let len = scanInfoList.length;
        console.log("wifi received scan info: " + len);
		if(len > 0){
			for (let i = 0; i < len; ++i) {
				console.info("ssid: " + scanInfoList[i].ssid);
				console.info("bssid: " + scanInfoList[i].bssid);
				console.info("capabilities: " + scanInfoList[i].capabilities);
				console.info("securityType: " + scanInfoList[i].securityType);
				console.info("rssi: " + scanInfoList[i].rssi);
				console.info("band: " + scanInfoList[i].band);
				console.info("frequency: " + scanInfoList[i].frequency);
				console.info("channelWidth: " + scanInfoList[i].channelWidth);
				console.info("timestamp: " + scanInfoList[i].timestamp);
			}
		}	
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}
	

WifiScanInfo9+

Represents WLAN hotspot information.

System capability: SystemCapability.Communication.WiFi.STA

NameTypeReadableWritableDescription
ssidstringYesNoService set identifier (SSID) of the hotspot, in UTF-8 format.
bssidstringYesNoBasic service set identifier (BSSID) of the hotspot.
bssidType10+DeviceAddressTypeYesNoBSSID type of the hotspot.
capabilitiesstringYesNoHotspot capabilities.
securityTypeWifiSecurityTypeYesNoWLAN security type.
rssinumberYesNoReceived signal strength indicator (RSSI) of the hotspot, in dBm.
bandnumberYesNoFrequency band of the WLAN access point (AP).
frequencynumberYesNoFrequency of the WLAN AP.
channelWidthnumberYesNoChannel width of the WLAN AP.
centerFrequency0numberYesNoCenter frequency of the hotspot.
centerFrequency1numberYesNoCenter frequency of the hotspot. If the hotspot uses two non-overlapping WLAN channels, two center frequencies, namely centerFrequency0 and centerFrequency1, are returned.
infoElemsArray<WifiInfoElem>YesNoInformation elements.
timestampnumberYesNoTimestamp.

DeviceAddressType 10+

Enumerates the Wi-Fi device address (MAC/BSSID) types.

System capability: SystemCapability.Communication.WiFi.Core

NameValueDescription
RANDOM_DEVICE_ADDRESS0Random device address.
REAL_DEVICE_ADDRESS1Read device address.

WifiSecurityType9+

Enumerates the WLAN security types.

System capability: SystemCapability.Communication.WiFi.Core

NameValueDescription
WIFI_SEC_TYPE_INVALID0Invalid security type.
WIFI_SEC_TYPE_OPEN1Open security type.
WIFI_SEC_TYPE_WEP2Wired Equivalent Privacy (WEP).
WIFI_SEC_TYPE_PSK3Pre-shared key (PSK).
WIFI_SEC_TYPE_SAE4Simultaneous Authentication of Equals (SAE).
WIFI_SEC_TYPE_EAP9+5Extensible Authentication protocol (EAP).
WIFI_SEC_TYPE_EAP_SUITE_B9+6Suite B 192-bit encryption.
WIFI_SEC_TYPE_OWE9+7Opportunistic Wireless Encryption (OWE).
WIFI_SEC_TYPE_WAPI_CERT9+8WLAN Authentication and Privacy Infrastructure (WAPI) in certificate-based mode (WAPI-CERT).
WIFI_SEC_TYPE_WAPI_PSK9+9WAPI-PSK.

WifiBandType10+

Enumerates the Wi-Fi band types.

System capability: SystemCapability.Communication.WiFi.STA

NameValueDescription
WIFI_BAND_NONE0Invalid band type
WIFI_BAND_2G12.4 GHz
WIFI_BAND_5G25 GHz
WIFI_BAND_6G36 GHz
WIFI_BAND_60G460 GHz

WifiStandard10+

Enumerates the Wi-Fi standards.

System capability: SystemCapability.Communication.WiFi.STA

NameValueDescription
WIFI_STANDARD_UNDEFINED0Invalid Wi-Fi standard
WIFI_STANDARD_11A1802.11a
WIFI_STANDARD_11B2802.11b
WIFI_STANDARD_11G3802.11g
WIFI_STANDARD_11N4802.11n
WIFI_STANDARD_11AC5802.11ac
WIFI_STANDARD_11AX6802.11ax
WIFI_STANDARD_11AD7802.11ad

WifiInfoElem9+

Represents a WLAN information element.

System capability: SystemCapability.Communication.WiFi.STA

NameTypeReadableWritableDescription
eidnumberYesNoID of the information element.
contentUint8ArrayYesNoContent of the information element.

WifiChannelWidth9+

Enumerates the WLAN channel widths.

System capability: SystemCapability.Communication.WiFi.STA

NameValueDescription
WIDTH_20MHZ020 MHz
WIDTH_40MHZ140 MHz
WIDTH_80MHZ280 MHz
WIDTH_160MHZ3160 MHz
WIDTH_80MHZ_PLUS480 MHz+
WIDTH_INVALID5Invalid value

wifiManager.setScanAlwaysAllowed10+

setScanAlwaysAllowed(isScanAlwaysAllowed: boolean): void

Sets whether scan is always allowed.

System API: This is a system API.

Required permissions: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
isScanAlwaysAllowedbooleanYesWhether scan is always allowed.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.
	import wifiManager from '@ohos.wifiManager';

	try {
		let isScanAlwaysAllowed = true;
		wifiManager.setScanAlwaysAllowed(isScanAlwaysAllowed);
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.getScanAlwaysAllowed10+

getScanAlwaysAllowed(): boolean

Obtains whether scan is always allowed.

System API: This is a system API.

Required permissions: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG

System capability: SystemCapability.Communication.WiFi.STA

Return value

TypeDescription
booleanWhether scan is always allowed. The value true means scan is allowed; the value false means the opposite.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let isScanAlwaysAllowed = wifiManager.getScanAlwaysAllowed();
		console.info("isScanAlwaysAllowed:" + isScanAlwaysAllowed);
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.addDeviceConfig9+

addDeviceConfig(config: WifiDeviceConfig): Promise<number>

Adds network configuration. This API uses a promise to return the result.

System API: This is a system API.

Required permissions: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
configWifiDeviceConfigYesWLAN configuration to add. The default bssidType is random device address.

Return value

TypeDescription
Promise<number>Promise used to return the ID of the added network configuration. If -1 is returned, the network configuration fails to be added.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let config:wifiManager.WifiDeviceConfig = {
			ssid : "****",
			preSharedKey : "****",
			securityType : 0
		}
		wifiManager.addDeviceConfig(config).then(result => {
			console.info("result:" + JSON.stringify(result));
		});	
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

WifiDeviceConfig9+

Represents the WLAN configuration.

System capability: SystemCapability.Communication.WiFi.STA

NameTypeReadableWritableDescription
ssidstringYesNoSSID of the hotspot, in UTF-8 format.
bssidstringYesNoBSSID of the hotspot.
bssidType10+DeviceAddressTypeYesNoBSSID type of the hotspot.
preSharedKeystringYesNoPSK of the hotspot.
isHiddenSsidbooleanYesNoWhether the network is hidden.
securityTypeWifiSecurityTypeYesNoSecurity type.
creatorUidnumberYesNoID of the creator.
System API: This is a system API.
disableReasonnumberYesNoReason for disabling WLAN.
System API: This is a system API.
netIdnumberYesNoNetwork ID.
System API: This is a system API.
randomMacTypenumberYesNoType of the MAC address.
The value 0 indicates random MAC address, and 1 indicates device MAC address.
System API: This is a system API.
randomMacAddrstringYesNoMAC address.
System API: This is a system API.
ipTypeIpTypeYesNoIP address type.
System API: This is a system API.
staticIpIpConfigYesNoStatic IP address information.
System API: This is a system API.
eapConfig10+WifiEapConfigYesNoEAP configuration.
proxyConfig10+WifiProxyConfigYesNoProxy configuration.
System API: This is a system API.

IpType9+

Enumerates the IP address types.

System API: This is a system API.

System capability: SystemCapability.Communication.WiFi.STA

NameValueDescription
STATIC0Static IP address.
DHCP1IP address allocated by DHCP.
UNKNOWN2Not specified.

IpConfig9+

Represents IP configuration information.

System API: This is a system API.

System capability: SystemCapability.Communication.WiFi.STA

NameTypeReadableWritableDescription
ipAddressnumberYesNoIP address.
gatewaynumberYesNoGateway.
prefixLengthnumberYesNoSubnet mask.
dnsServersnumber[]YesNoDomain name server (DNS) information.
domainsArray<string>YesNoDomain information.

WifiEapConfig10+

Represents EAP configuration information.

System capability: SystemCapability.Communication.WiFi.STA

NameTypeReadableWritableDescription
eapMethodEapMethodYesNoEAP authentication method.
phase2MethodPhase2MethodYesNoPhase 2 authentication method.
identitystringYesNoIdentity Information.
anonymousIdentitystringYesNoAnonymous identity.
passwordstringYesNoPassword.
caCertAliasstringYesNoCA certificate alias.
caPathstringYesNoCA certificate path.
clientCertAliasstringYesNoClient certificate alias.
certEntryUint8ArrayYesYesCA certificate content.
certPasswordstringYesYesCA certificate password.
altSubjectMatchstringYesNoA string to match the alternate subject.
domainSuffixMatchstringYesNoA string to match the domain suffix.
realmstringYesNoRealm for the passpoint credential.
plmnstringYesNoPublic land mobile network (PLMN) of the passpoint credential provider.
eapSubIdnumberYesNoSub-ID of the SIM card.

EapMethod10+

Enumerates the EAP authentication methods.

System capability: SystemCapability.Communication.WiFi.STA

NameValueDescription
EAP_NONE0Not specified.
EAP_PEAP1PEAP.
EAP_TLS2TLS.
EAP_TTLS3TTLS.
EAP_PWD4Password.
EAP_SIM5SIM.
EAP_AKA6AKA.
EAP_AKA_PRIME7AKA Prime.
EAP_UNAUTH_TLS8UNAUTH TLS.

Phase2Method10+

Enumerates the Phase 2 authentication methods.

System capability: SystemCapability.Communication.WiFi.STA

NameValueDescription
PHASE2_NONE0Not specified.
PHASE2_PAP1PAP.
PHASE2_MSCHAP2MS-CHAP.
PHASE2_MSCHAPV23MS-CHAPv2.
PHASE2_GTC4GTC .
PHASE2_SIM5SIM.
PHASE2_AKA6AKA.
PHASE2_AKA_PRIME7AKA Prime.

WifiProxyConfig 10+

Represents the Wi-Fi proxy configuration.

System API: This is a system API.

System capability: SystemCapability.Communication.WiFi.STA

NameTypeReadableWritableDescription
proxyMethodProxyMethodYesNoProxy method.
pacWebAddressstringYesNoPAC web address of the proxy automatically configured.
serverHostNamestringYesNoServer host name of the proxy manually configured.
serverPortstringYesNoServer port of the proxy manually configured.
exclusionObjectsstringYesNoExcluded objects of the manually configured proxy. Multiple objects are separated by commas (,).

ProxyMethod10+

Enumerates the Wi-Fi proxy methods.

System API: This is a system API.

System capability: SystemCapability.Communication.WiFi.STA

NameValueDescription
METHOD_NONE0No proxy.
METHOD_AUTO1Use an automatically configured proxy.
METHOD_MANUAL2Use a manually configured proxy.

wifiManager.addDeviceConfig9+

addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void

Adds network configuration. This API uses an asynchronous callback to return the result.

System API: This is a system API.

Required permissions: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
configWifiDeviceConfigYesWLAN configuration to add. The default bssidType is random device address.
callbackAsyncCallback<number>YesCallback invoked to return the result. If the operation is successful, err is 0 and data is the network configuration ID. If data is -1, the operation has failed. If err is not 0, an error has occurred.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let config:wifiManager.WifiDeviceConfig = {
			ssid : "****",
			preSharedKey : "****",
			securityType : 0
		}
		wifiManager.addDeviceConfig(config,(error,result) => {
			console.info("result:" + JSON.stringify(result));
		});	
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.addCandidateConfig9+

addCandidateConfig(config: WifiDeviceConfig): Promise<number>

Adds the configuration of a candidate network. This API uses a promise to return the result.

Required permissions: ohos.permission.SET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
configWifiDeviceConfigYesWLAN configuration to add. The default bssidType is random device address.

Return value

TypeDescription
Promise<number>Promise used to return the network configuration ID.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let config:wifiManager.WifiDeviceConfig = {
			ssid : "****",
			preSharedKey : "****",
			securityType : 0
		}
		wifiManager.addCandidateConfig(config).then(result => {
			console.info("result:" + JSON.stringify(result));
		});	
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.addCandidateConfig9+

addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void

Adds the configuration of a candidate network. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.SET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
configWifiDeviceConfigYesWLAN configuration to add. The default bssidType is random device address.
callbackAsyncCallback<number>YesCallback invoked to return the result. If the operation is successful, err is 0 and data is the network configuration ID. If data is -1, the operation has failed. If err is not 0, an error has occurred.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let config:wifiManager.WifiDeviceConfig = {
			ssid : "****",
			preSharedKey : "****",
			securityType : 0
		}
		wifiManager.addCandidateConfig(config,(error,result) => {
			console.info("result:" + JSON.stringify(result));
		});	
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.removeCandidateConfig9+

removeCandidateConfig(networkId: number): Promise<void>

Removes the configuration of a candidate network. This API uses a promise to return the result.

Required permissions: ohos.permission.SET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
networkIdnumberYesID of the network configuration to remove.

Return value

TypeDescription
Promise<void>Promise used to return the result.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let networkId = 0;
		wifiManager.removeCandidateConfig(networkId).then(result => {
			console.info("result:" + JSON.stringify(result));
		});	
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.removeCandidateConfig9+

removeCandidateConfig(networkId: number, callback: AsyncCallback<void>): void

Removes the configuration of a candidate network. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.SET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
networkIdnumberYesID of the network configuration to remove.
callbackAsyncCallback<void>YesCallback invoked to return the result. If the operation is successful, err is 0. If err is not 0, an error has occurred.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let networkId = 0;
		wifiManager.removeCandidateConfig(networkId,(error,result) => {
		console.info("result:" + JSON.stringify(result));
		});	
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.getCandidateConfigs9+

getCandidateConfigs():  Array<WifiDeviceConfig>

Obtains candidate network configuration.

Required permissions:

API version 9: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION

API version 10 and later : ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Return value

TypeDescription
 Array<WifiDeviceConfig>Candidate network configuration obtained.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let configs = wifiManager.getCandidateConfigs();
		console.info("configs:" + JSON.stringify(configs));
		let len = configs.length;
        console.log("result len: " + len);
		if(len > 0){
			for (let i = 0; i < len; ++i) {
				console.info("ssid: " + configs[i].ssid);
				console.info("bssid: " + configs[i].bssid);
			}
		}	
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}
	

wifiManager.connectToCandidateConfig9+

connectToCandidateConfig(networkId: number): void

Connects to a candidate network added by the application. If the device is already connected to a hotspot, disconnect it from the hotspot first.

Required permissions: ohos.permission.SET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
networkIdnumberYesID of the candidate network configuration.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.
2501001Wifi is closed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let networkId = 0;
		let ret = wifiManager.connectToCandidateConfig(networkId);
		console.info("result:" + ret);
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}
	

wifiManager.connectToNetwork9+

connectToNetwork(networkId: number): void

Connects to the specified network. If the device is already connected to a hotspot, use disconnect() to disconnect it from the hotspot first.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications)

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
networkIdnumberYesNetwork configuration ID.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.
2501001Wifi is closed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let networkId = 0;
		wifiManager.connectToNetwork(networkId);
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}	

wifiManager.connectToDevice9+

connectToDevice(config: WifiDeviceConfig): void

Connects to the specified network. If the device is already connected to a hotspot, use disconnect() to disconnect it from the hotspot first.

System API: This is a system API.

Required permissions: ohos.permission.SET_WIFI_INFO, ohos.permission.SET_WIFI_CONFIG, and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications)

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
configWifiDeviceConfigYesConfiguration of the WLAN to connect. The default bssidType is random device address.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.
2501001Wifi is closed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let config:wifiManager.WifiDeviceConfig = {
			ssid : "****",
			preSharedKey : "****",
			securityType : 3
		}
		wifiManager.connectToDevice(config);
				
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.disconnect9+

disconnect(): void

Disconnects the network.

System API: This is a system API.

Required permissions: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications)

System capability: SystemCapability.Communication.WiFi.STA

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		wifiManager.disconnect();
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.getSignalLevel9+

getSignalLevel(rssi: number, band: number): number

Obtains the WLAN signal level.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
rssinumberYesRSSI of the hotspot, in dBm.
bandnumberYesFrequency band of the WLAN AP.

Return value

TypeDescription
numberSignal level obtained. The value range is [0, 4].

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let rssi = 0;
		let band = 0;
		let level = wifiManager.getSignalLevel(rssi,band);
		console.info("level:" + JSON.stringify(level));
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.getLinkedInfo9+

getLinkedInfo(): Promise<WifiLinkedInfo>

Obtains WLAN connection information. This API uses a promise to return the result.

Required permissions: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_LOCAL_MAC (if macAddress needs to be obtained; otherwise, macAddress is an empty string.)

System capability: SystemCapability.Communication.WiFi.STA

Return value

TypeDescription
Promise<WifiLinkedInfo>Promise used to return the WLAN connection information obtained.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.
2501001Wifi is closed.

wifiManager.getLinkedInfo9+

getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void

Obtains WLAN connection information. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_LOCAL_MAC (if macAddress needs to be obtained; otherwise, macAddress is an empty string.)

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<WifiLinkedInfo>YesCallback invoked to return the result. If the operation is successful, err is 0 and data is the WLAN connection information obtained. If err is not 0, an error has occurred.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.
2501001Wifi is closed.

Example

  import wifiManager from '@ohos.wifiManager';
  
  wifiManager.getLinkedInfo((err, data) => {
      if (err) {
          console.error("get linked info error");
          return;
      }
      console.info("get wifi linked info: " + JSON.stringify(data));
  });
  
  wifiManager.getLinkedInfo().then(data => {
      console.info("get wifi linked info: " + JSON.stringify(data));
  }).catch((error:number) => {
      console.info("get linked info error");
  });

WifiLinkedInfo9+

Represents the WLAN connection information.

System capability: SystemCapability.Communication.WiFi.STA

NameTypeReadableWritableDescription
ssidstringYesNoSSID of the hotspot, in UTF-8 format.
bssidstringYesNoBSSID of the hotspot.
networkIdnumberYesNoNetwork configuration ID.
System API: This is a system API.
rssinumberYesNoRSSI of the hotspot, in dBm.
bandnumberYesNoBand of the WLAN AP.
linkSpeednumberYesNoUplink speed of the WLAN AP.
rxLinkSpeed10+numberYesNoDownlink speed of the WLAN AP.
maxSupportedTxLinkSpeed10+numberYesNoMaximum uplink speed supported.
maxSupportedRxLinkSpeed10+numberYesNoMaximum uplink speed supported.
frequencynumberYesNoFrequency of the WLAN AP.
isHiddenbooleanYesNoWhether to hide the WLAN AP.
isRestrictedbooleanYesNoWhether to restrict data volume at the WLAN AP.
chloadnumberYesNoChannel load. A larger value indicates a higher load.
System API: This is a system API.
snrnumberYesNoSignal-to-noise ratio (SNR).
System API: This is a system API.
macTypenumberYesNoMAC address type.
The value 0 indicates random MAC address, and 1 indicates device MAC address.
macAddressstringYesNoMAC address of the device.
ipAddressnumberYesNoIP address of the device that sets up the WLAN connection.
suppStateSuppStateYesNoSupplicant state.
System API: This is a system API.
connStateConnStateYesNoWLAN connection state.
channelWidth10+WifiChannelWidthYesNoChannel bandwidth of the connected hotspot.
wifiStandard10+WifiStandardYesNoWi-Fi standard used by the connected hotspot.

ConnState9+

Enumerates the WLAN connection states.

System capability: SystemCapability.Communication.WiFi.STA

NameValueDescription
SCANNING0The device is scanning for available APs.
CONNECTING1A WLAN connection is being established.
AUTHENTICATING2An authentication is being performed for a WLAN connection.
OBTAINING_IPADDR3The IP address of the WLAN connection is being acquired.
CONNECTED4A WLAN connection is established.
DISCONNECTING5The WLAN connection is being disconnected.
DISCONNECTED6The WLAN connection is disconnected.
UNKNOWN7Failed to set up the WLAN connection.

SuppState9+

Enumerates the supplicant states.

System API: This is a system API.

System capability: SystemCapability.Communication.WiFi.STA

NameValueDescription
DISCONNECTED0The supplicant is disconnected from the AP.
INTERFACE_DISABLED1The network interface is disabled.
INACTIVE2The supplicant is inactive.
SCANNING3The supplicant is scanning for a WLAN connection.
AUTHENTICATING4The supplicant is being authenticated.
ASSOCIATING5The supplicant is being associated with an AP.
ASSOCIATED6The supplicant is associated with an AP.
FOUR_WAY_HANDSHAKE7A four-way handshake is being performed for the supplicant.
GROUP_HANDSHAKE8A group handshake is being performed for the supplicant.
COMPLETED9The authentication is complete.
UNINITIALIZED10The supplicant failed to set up the connection.
INVALID11Invalid value.

wifiManager.isConnected9+

isConnected(): boolean

Checks whether the WLAN is connected.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Return value

TypeDescription
booleanReturns true if the WLAN is connected; returns false otherwise.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let ret = wifiManager.isConnected();
		console.info("isConnected:" + ret);
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.getSupportedFeatures9+

getSupportedFeatures(): number

Obtains the features supported by this device.

System API: This is a system API.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.Core

Return value

TypeDescription
numberFeature value.

Feature IDs

ValueDescription
0x0001WLAN infrastructure mode
0x00025 GHz feature
0x0004Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature
0x0008Wi-Fi Direct
0x0010SoftAP
0x0040Wi-Fi Aware
0x8000WLAN AP/STA concurrency
0x8000000WPA3 Personal (WPA-3 SAE)
0x10000000WPA3-Enterprise Suite B
0x20000000Enhanced open feature

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2401000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let ret = wifiManager.getSupportedFeatures();
		console.info("supportedFeatures:" + ret);
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.isFeatureSupported9+

isFeatureSupported(featureId: number): boolean

Checks whether the device supports the specified WLAN feature.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.Core

Parameters

NameTypeMandatoryDescription
featureIdnumberYesFeature ID.

Return value

TypeDescription
booleanReturns true if the feature is supported; returns false otherwise.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2401000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let featureId = 0;
		let ret = wifiManager.isFeatureSupported(featureId);
		console.info("isFeatureSupported:" + ret);
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.getDeviceMacAddress9+

getDeviceMacAddress(): string[]

Obtains the device MAC address.

System API: This is a system API.

Required permissions: ohos.permission.GET_WIFI_LOCAL_MAC and ohos.permission.GET_WIFI_INFO (available only to system applications)

System capability: SystemCapability.Communication.WiFi.STA

Return value

TypeDescription
string[]MAC address obtained.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.
2501001wifi is closed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let ret = wifiManager.getDeviceMacAddress();
		console.info("deviceMacAddress:" + JSON.stringify(ret));
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.getIpInfo9+

getIpInfo(): IpInfo

Obtains IP information.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Return value

TypeDescription
IpInfoIP information obtained.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let info = wifiManager.getIpInfo();
		console.info("info:" + JSON.stringify(info));
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

IpInfo9+

Represents IP information.

System capability: SystemCapability.Communication.WiFi.STA

NameTypeReadableWritableDescription
ipAddressnumberYesNoIP address.
gatewaynumberYesNoGateway.
netmasknumberYesNoSubnet mask.
primaryDnsnumberYesNoIP address of the preferred DNS server.
secondDnsnumberYesNoIP address of the alternate DNS server.
serverIpnumberYesNoIP address of the DHCP server.
leaseDurationnumberYesNoLease duration of the IP address.

wifiManager.getIpv6Info10+

getIpv6Info(): Ipv6Info

Obtains IP information.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Return value

TypeDescription
Ipv6InfoIPv6 information obtained.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let info = wifiManager.getIpv6Info();
		console.info("info:" + JSON.stringify(info));
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

Ipv6Info 10+

Represents the IPv6 information.

System capability: SystemCapability.Communication.WiFi.STA

NameTypeReadableWritableDescription
linkIpv6AddressstringYesNoIPv6 address of the link.
globalIpv6AddressstringYesNoGlobal IPv6 address.
randomGlobalIpv6AddressstringYesNoRandom global IPv6 address.
gatewaystringYesNoGateway IP address.
netmaskstringYesNoSubnet mask.
primaryDNSstringYesNoIPv6 address of the preferred DNS server.
secondDNSstringYesNoIPv6 address of the alternate DNS server.

wifiManager.getCountryCode9+

getCountryCode(): string

Obtains the country code.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.Core

Return value

TypeDescription
stringCountry code obtained.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2401000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let code = wifiManager.getCountryCode();
		console.info("code:" + code);
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.reassociate9+

reassociate(): void

Re-associates with the network.

System API: This is a system API.

Required permissions: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications)

System capability: SystemCapability.Communication.WiFi.STA

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.
2501001Wifi is closed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		wifiManager.reassociate();
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.reconnect9+

reconnect(): void

Reconnects to the network.

System API: This is a system API.

Required permissions: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications)

System capability: SystemCapability.Communication.WiFi.STA

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.
2501001Wifi is closed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		wifiManager.reconnect();
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.getDeviceConfigs9+

getDeviceConfigs():  Array<WifiDeviceConfig>

Obtains network configuration.

System API: This is a system API.

Required permissions:

API version 9: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, ohos.permission.APPROXIMATELY_LOCATION, and ohos.permission.GET_WIFI_CONFIG

API version 10 and later: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG

System capability: SystemCapability.Communication.WiFi.STA

Return value

TypeDescription
 Array<WifiDeviceConfig>Array of network configuration obtained.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let configs = wifiManager.getDeviceConfigs();
		console.info("configs:" + JSON.stringify(configs));
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.updateNetwork9+

updateNetwork(config: WifiDeviceConfig): number

Updates network configuration.

System API: This is a system API.

Required permissions: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
configWifiDeviceConfigYesNew WLAN configuration.

Return value

TypeDescription
numberID of the updated network configuration. The value -1 indicates that the operation has failed.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let config:wifiManager.WifiDeviceConfig = {
			ssid : "****",
			preSharedKey : "****",
			securityType : 3
		}
		let ret = wifiManager.updateNetwork(config);
		console.info("ret:" + ret);
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.disableNetwork9+

disableNetwork(netId: number): void

Disables network configuration.

System API: This is a system API.

Required permissions: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications)

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
netIdnumberYesID of the network configuration to disable.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let netId = 0;
		wifiManager.disableNetwork(netId);		
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.removeAllNetwork9+

removeAllNetwork(): void

Removes the configuration of all networks.

System API: This is a system API.

Required permissions: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications)

System capability: SystemCapability.Communication.WiFi.STA

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		wifiManager.removeAllNetwork();		
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.removeDevice9+

removeDevice(id: number): void

Removes the specified network configuration.

System API: This is a system API.

Required permissions: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications)

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
idnumberYesID of the network configuration to remove.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let id = 0;
		wifiManager.removeDevice(id);		
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.isBandTypeSupported10+

isBandTypeSupported(bandType: WifiBandType): boolean

Checks whether the current frequency band is supported.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
bandTypeWifiBandTypeYesWi-Fi band type.

Return value

TypeDescription
booleanReturns true if the feature is supported; returns false otherwise.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let type = 0;
		let isBandTypeSupported = wifiManager.isBandTypeSupported(type);
		console.info("isBandTypeSupported:" + isBandTypeSupported);		
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.get5GChannelList10+

get5GChannelList(): Array<number>

Obtains the list of 5 GHz channels supported by this device.

System API: This is a system API.

Required permissions: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG

System capability: SystemCapability.Communication.WiFi.STA

Return value

TypeDescription
 Array<number>List of 5 GHz channels supported by the device.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let channelList = wifiManager.get5GChannelList();
		console.info("channelList:" + JSON.stringify(channelList));		
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.getDisconnectedReason10+

getDisconnectedReason(): DisconnectedReason

Obtains the reason of the latest disconnection.

System API: This is a system API.

Required permissions: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG

System capability: SystemCapability.Communication.WiFi.STA

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Return value

TypeDescription
DisconnectedReasonReturns the reason of the latest disconnection obtained.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let disconnectedReason = wifiManager.getDisconnectedReason();	
        console.info("disconnectedReason:" + disconnectedReason);
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

DisconnectedReason 10+

Enumerates the Wi-Fi disconnection reasons.

System API: This is a system API.

System capability: SystemCapability.Communication.WiFi.STA

NameValueDescription
DISC_REASON_DEFAULT0Default reason.
DISC_REASON_WRONG_PWD1Incorrect password.
DISC_REASON_CONNECTION_FULL2The number of connections to the router has reached the limit.

wifiManager.enableHotspot9+

enableHotspot(): void

Enables this hotspot. This API is an asynchronous interface. The hotspotStateChange callback must be registered and listened for.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications)

System capability: SystemCapability.Communication.WiFi.AP.Core

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2601000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		wifiManager.enableHotspot();	
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.disableHotspot9+

disableHotspot(): void

Disables this hotspot. This API is an asynchronous interface. The hotspotStateChange callback must be registered and listened for.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications)

System capability: SystemCapability.Communication.WiFi.AP.Core

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2601000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		wifiManager.disableHotspot();	
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.isHotspotDualBandSupported9+

isHotspotDualBandSupported(): boolean

Checks whether the hotspot supports dual band.

System API: This is a system API.

Required permissions: ohos.permission.GET_WIFI_INFO and ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications)

System capability: SystemCapability.Communication.WiFi.AP.Core

Return value

TypeDescription
booleanReturns true if the hotspot supports dual band; returns false otherwise.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2601000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let ret = wifiManager.isHotspotDualBandSupported();
		console.info("result:" + ret);		
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.isHotspotActive9+

isHotspotActive(): boolean

Checks whether this hotspot is active.

System API: This is a system API.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.AP.Core

Return value

TypeDescription
booleanReturns true if the hotspot is active; returns false otherwise.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2601000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let ret = wifiManager.isHotspotActive();
		console.info("result:" + ret);		
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.setHotspotConfig9+

setHotspotConfig(config: HotspotConfig): void

Sets hotspot configuration.

System API: This is a system API.

Required permissions: ohos.permission.SET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG

System capability: SystemCapability.Communication.WiFi.AP.Core

Parameters

NameTypeMandatoryDescription
configHotspotConfigYesHotspot configuration to set.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2601000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let config:wifiManager.HotspotConfig = {
			ssid: "****",
			securityType: 3,
			band: 0,
			channel: 0,
			preSharedKey: "****",
			maxConn: 0
		}
		let ret = wifiManager.setHotspotConfig(config);
		console.info("result:" + ret);		
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

HotspotConfig9+

Represents the hotspot configuration.

System API: This is a system API.

System capability: SystemCapability.Communication.WiFi.AP.Core

NameTypeReadableWritableDescription
ssidstringYesYesSSID of the hotspot, in UTF-8 format.
securityTypeWifiSecurityTypeYesYesSecurity type.
bandnumberYesYesHotspot band. The value 1 stands for 2.4 GHz, the value 2 for 5 GHz, and the value 3 for dual band.
channel10+numberYesYesHotspot channel (2.4 GHz: 1 to 14; 5 GHz: 7 to 196; Dual-band: not supported currently)
preSharedKeystringYesYesPSK of the hotspot.
maxConnnumberYesYesMaximum number of connections allowed.

wifiManager.getHotspotConfig9+

getHotspotConfig(): HotspotConfig

Obtains hotspot configuration.

System API: This is a system API.

Required permissions: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG

System capability: SystemCapability.Communication.WiFi.AP.Core

Return value

TypeDescription
HotspotConfigHotspot configuration obtained.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2601000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let config = wifiManager.getHotspotConfig();
		console.info("result:" + JSON.stringify(config));		
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.getStations9+

getStations():  Array<StationInfo>

Obtains information about the connected stations.

System API: This is a system API.

Required permissions:

API version 9: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, ohos.permission.APPROXIMATELY_LOCATION, and ohos.permission.MANAGE_WIFI_HOTSPOT (for system applications only)

API version 10 and later: ohos.permission.GET_WIFI_INFO and ohos.permission.MANAGE_WIFI_HOTSPOT (for system applications only)

System capability: SystemCapability.Communication.WiFi.AP.Core

Return value

TypeDescription
 Array<StationInfo>Connected stations obtained. If the application has the ohos.permission.GET_WIFI_PEERS_MAC permission, macAddress in the return value is a real MAC address; otherwise, macAddress is a random MAC address.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2601000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let stations = wifiManager.getStations();
		console.info("result:" + JSON.stringify(stations));		
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

StationInfo9+

Represents the station information.

System API: This is a system API.

System capability: SystemCapability.Communication.WiFi.AP.Core

NameTypeReadableWritableDescription
namestringYesNoDevice name.
macAddressstringYesNoMAC address.
macAddressType10+DeviceAddressTypeYesNoMAC address type.
ipAddressstringYesNoIP address.

wifiManager.getP2pLinkedInfo9+

getP2pLinkedInfo(): Promise<WifiP2pLinkedInfo>

Obtains P2P link information. This API uses a promise to return the result.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Return value

TypeDescription
Promise<WifiP2pLinkedInfo>Promise used to return the P2P link information obtained.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	wifiManager.getP2pLinkedInfo((err, data) => {
    if (err) {
        console.error("get p2p linked info error");
        return;
    }
		console.info("get wifi p2p linked info: " + JSON.stringify(data));
	});

	wifiManager.getP2pLinkedInfo().then(data => {
		console.info("get wifi p2p linked info: " + JSON.stringify(data));
	});

WifiP2pLinkedInfo9+

Represents the P2P link information.

System capability: SystemCapability.Communication.WiFi.P2P

NameTypeReadableWritableDescription
connectStateP2pConnectStateYesNoP2P connection state.
isGroupOwnerbooleanYesNoWhether the device is the group owner.
groupOwnerAddrstringYesNoMAC address of the group.

P2pConnectState9+

Enumerates the P2P connection states.

System capability: SystemCapability.Communication.WiFi.P2P

NameValueDescription
DISCONNECTED0Disconnected.
CONNECTED1Connected.

wifiManager.getP2pLinkedInfo9+

getP2pLinkedInfo(callback: AsyncCallback<WifiP2pLinkedInfo>): void

Obtains P2P link information. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<WifiP2pLinkedInfo>YesCallback invoked to return the result. If the operation is successful, err is 0 and data is the P2P link information. If err is not 0, an error has occurred.

wifiManager.getCurrentGroup9+

getCurrentGroup(): Promise<WifiP2pGroupInfo>

Obtains the current P2P group information. This API uses a promise to return the result.

Required permissions:

API version 9: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION

API version 10 and later : ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Return value

TypeDescription
Promise<WifiP2pGroupInfo>Promise used to return the P2P group information obtained. If the application has the ohos.permission.GET_WIFI_PEERS_MAC permission, deviceAddress in the return value is a real device address; otherwise, deviceAddress is a random device address.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

wifiManager.getCurrentGroup9+

getCurrentGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void

Obtains the current P2P group information. This API uses an asynchronous callback to return the result.

Required permissions:

API version 9: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION

API version 10 and later : ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<WifiP2pGroupInfo>YesCallback invoked to return the result. If the operation is successful, err is 0 and data is the group information obtained. If err is not 0, an error has occurred. If the application has the ohos.permission.GET_WIFI_PEERS_MAC permission, deviceAddress in the return value is a real device address; otherwise, deviceAddress is a random device address.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	wifiManager.getCurrentGroup((err, data) => {
    if (err) {
        console.error("get current P2P group error");
        return;
    }
		console.info("get current P2P group: " + JSON.stringify(data));
	});

	wifiManager.getCurrentGroup().then(data => {
		console.info("get current P2P group: " + JSON.stringify(data));
	});

wifiManager.getP2pPeerDevices9+

getP2pPeerDevices(): Promise<WifiP2pDevice[]>

Obtains the peer device list in the P2P connection. This API uses a promise to return the result.

Required permissions:

API version 9: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION

API version 10 and later : ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Return value

TypeDescription
Promise<WifiP2pDevice[]>Promise used to return the peer device list. If the application has the ohos.permission.GET_WIFI_PEERS_MAC permission, deviceAddress in the return value is a real device address; otherwise, deviceAddress is a random device address.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

wifiManager.getP2pPeerDevices9+

getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void

Obtains the peer device list in the P2P connection. This API uses an asynchronous callback to return the result.

Required permissions:

API version 9: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION

API version 10 and later : ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<WifiP2pDevice[]>YesCallback invoked to return the result. If the operation is successful, err is 0 and data is the peer device list obtained. If err is not 0, an error has occurred. If the application has the ohos.permission.GET_WIFI_PEERS_MAC permission, deviceAddress in the return value is a real device address; otherwise, deviceAddress is a random device address.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	wifiManager.getP2pPeerDevices((err, data) => {
    if (err) {
        console.error("get P2P peer devices error");
        return;
    }
		console.info("get P2P peer devices: " + JSON.stringify(data));
	});

	wifiManager.getP2pPeerDevices().then(data => {
		console.info("get P2P peer devices: " + JSON.stringify(data));
	});

WifiP2pDevice9+

Represents the P2P device information.

System capability: SystemCapability.Communication.WiFi.P2P

NameTypeReadableWritableDescription
deviceNamestringYesNoDevice name.
deviceAddressstringYesNoMAC address of the device.
deviceAddressType10+DeviceAddressTypeYesNoMAC address type of the device.
primaryDeviceTypestringYesNoType of the primary device.
deviceStatusP2pDeviceStatusYesNoDevice status.
groupCapabilitiesnumberYesNoGroup capabilities.

P2pDeviceStatus9+

Enumerates the P2P device states.

System capability: SystemCapability.Communication.WiFi.P2P

NameValueDescription
CONNECTED0Connected.
INVITED1Invited.
FAILED2Failed.
AVAILABLE3Available.
UNAVAILABLE4Unavailable.

wifiManager.getP2pLocalDevice9+

getP2pLocalDevice(): Promise<WifiP2pDevice>

Obtains the local device information in the P2P connection. This API uses a promise to return the result.

Required permissions: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG

System capability: SystemCapability.Communication.WiFi.P2P

Return value

TypeDescription
Promise<WifiP2pDevice>Promise used to return the local device information obtained.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

wifiManager.getP2pLocalDevice9+

getP2pLocalDevice(callback: AsyncCallback<WifiP2pDevice>): void

Obtains the local device information in the P2P connection. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<WifiP2pDevice>YesCallback invoked to return the result. If the operation is successful, err is 0 and data is the local device information obtained. If err is not 0, an error has occurred.

Error codes

IDError Message
2801000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	wifiManager.getP2pLocalDevice((err, data) => {
    if (err) {
        console.error("get P2P local device error");
        return;
    }
		console.info("get P2P local device: " + JSON.stringify(data));
	});

	wifiManager.getP2pLocalDevice().then(data => {
		console.info("get P2P local device: " + JSON.stringify(data));
	});

wifiManager.createGroup9+

createGroup(config: WifiP2PConfig): void

Creates a P2P group.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
configWifiP2PConfigYesGroup configuration. The default DeviceAddressType is random device address.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let config:wifiManager.WifiP2PConfig = {
			deviceAddress: "****",
			netId: 0,
			passphrase: "*****",
			groupName: "****",
			goBand: 0
		}
		wifiManager.createGroup(config);	
		
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

WifiP2PConfig9+

Represents P2P group configuration.

System capability: SystemCapability.Communication.WiFi.P2P

NameTypeReadableWritableDescription
deviceAddressstringYesNoDevice address.
deviceAddressType10+DeviceAddressTypeYesNoDevice address type.
netIdnumberYesNoNetwork ID. The value -1 indicates a temporary group, and -2 indicates a persistent group.
passphrasestringYesNoPassphrase of the group.
groupNamestringYesNoName of the group.
goBandGroupOwnerBandYesNoFrequency band of the group.

GroupOwnerBand9+

Enumerates the P2P group frequency bands.

System capability: SystemCapability.Communication.WiFi.P2P

NameValueDescription
GO_BAND_AUTO0Auto.
GO_BAND_2GHZ12 GHz.
GO_BAND_5GHZ25 GHz.

wifiManager.removeGroup9+

removeGroup(): void

Removes this P2P group.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		wifiManager.removeGroup();	
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.p2pConnect9+

p2pConnect(config: WifiP2PConfig): void

Sets up a P2P connection.

Required permissions:

API version 9: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION

API version 10 and later : ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
configWifiP2PConfigYesP2P group configuration. The default DeviceAddressType is random device address.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

  import wifiManager from '@ohos.wifiManager';
  
  let recvP2pConnectionChangeFunc = (result:wifiManager.WifiP2pLinkedInfo) => {
      console.info("p2p connection change receive event: " + JSON.stringify(result));
      wifiManager.getP2pLinkedInfo((err, data) => {
          if (err) {
              console.error('failed to get getP2pLinkedInfo: ' + JSON.stringify(err));
              return;
          }
          console.info("get getP2pLinkedInfo: " + JSON.stringify(data));
      });
  }
  wifiManager.on("p2pConnectionChange", recvP2pConnectionChangeFunc);
  
  let recvP2pDeviceChangeFunc = (result:wifiManager.WifiP2pDevice) => {
      console.info("p2p device change receive event: " + JSON.stringify(result));
  }
  wifiManager.on("p2pDeviceChange", recvP2pDeviceChangeFunc);
  
  let recvP2pPeerDeviceChangeFunc = (result:wifiManager.WifiP2pDevice[]) => {
      console.info("p2p peer device change receive event: " + JSON.stringify(result));
      wifiManager.getP2pPeerDevices((err, data) => {
          if (err) {
              console.error('failed to get peer devices: ' + JSON.stringify(err));
              return;
          }
          console.info("get peer devices: " + JSON.stringify(data));
          let len = data.length;
          for (let i = 0; i < len; ++i) {
              if (data[i].deviceName === "my_test_device") {
                  console.info("p2p connect to test device: " + data[i].deviceAddress);
                  let config:wifiManager.WifiP2PConfig = {
                      deviceAddress:data[i].deviceAddress,
                      netId:-2,
                      passphrase:"",
                      groupName:"",
                      goBand:0,
                  }
                  wifiManager.p2pConnect(config);
              }
          }
      });
  }
  wifiManager.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);
  
  let recvP2pPersistentGroupChangeFunc = () => {
      console.info("p2p persistent group change receive event");
  
      wifiManager.getCurrentGroup((err, data) => {
          if (err) {
              console.error('failed to get current group: ' + JSON.stringify(err));
              return;
          }
          console.info("get current group: " + JSON.stringify(data));
      });
  }
  wifiManager.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);
  
  setTimeout(() => {wifiManager.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000);
  setTimeout(() =>  {wifiManager.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000);
  setTimeout(() =>  {wifiManager.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000);
  setTimeout(() =>  {wifiManager.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000);
  console.info("start discover devices -> " + wifiManager.startDiscoverDevices());

wifiManager.p2pCancelConnect9+

p2pCancelConnect(): void

Cancels this P2P connection.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		wifiManager.p2pCancelConnect();	
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.startDiscoverDevices9+

startDiscoverDevices(): void

Starts to discover devices.

Required permissions:

API version 9: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION

API version 10 and later : ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		wifiManager.startDiscoverDevices();	
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.stopDiscoverDevices9+

stopDiscoverDevices(): void

Stops discovering devices.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		wifiManager.stopDiscoverDevices();	
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.deletePersistentGroup9+

deletePersistentGroup(netId: number): void

Deletes a persistent group.

System API: This is a system API.

Required permissions: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
netIdnumberYesID of the group to delete.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let netId = 0;
		wifiManager.deletePersistentGroup(netId);	
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.getP2pGroups9+

getP2pGroups(): Promise<Array<WifiP2pGroupInfo>>

Obtains information about all P2P groups. This API uses a promise to return the result.

System API: This is a system API.

Required permissions:

API version 9: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION

API version 10 and later : ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Return value

TypeDescription
Promise< Array<WifiP2pGroupInfo> >Promise used to return the group information obtained. If the application has the ohos.permission.GET_WIFI_PEERS_MAC permission, deviceAddress in the return value is a real device address; otherwise, deviceAddress is a random device address.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	wifiManager.getP2pGroups((err, data) => {
    if (err) {
        console.error("get P2P groups error");
        return;
    }
		console.info("get P2P groups: " + JSON.stringify(data));
	});

	wifiManager.getP2pGroups().then(data => {
		console.info("get P2P groups: " + JSON.stringify(data));
	});
	

WifiP2pGroupInfo9+

Represents the P2P group information.

System capability: SystemCapability.Communication.WiFi.P2P

NameTypeReadableWritableDescription
isP2pGobooleanYesNoWhether the device is the group owner.
ownerInfoWifiP2pDeviceYesNoDevice information of the group.
passphrasestringYesNoPassphrase of the group.
interfacestringYesNoInterface name.
groupNamestringYesNoGroup name.
networkIdnumberYesNoNetwork ID.
frequencynumberYesNoFrequency of the group.
clientDevicesWifiP2pDevice[]YesNoList of connected devices.
goIpAddressstringYesNoIP address of the group.

wifiManager.getP2pGroups9+

getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void

Obtains information about all P2P groups. This API uses an asynchronous callback to return the result.

System API: This is a system API.

Required permissions:

API version 9: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION

API version 10 and later : ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback< Array<WifiP2pGroupInfo>>YesCallback invoked to return the result. If the operation is successful, err is 0 and data is the group information obtained. If err is not 0, an error has occurred. If the application has the ohos.permission.GET_WIFI_PEERS_MAC permission, deviceAddress in the return value is a real device address; otherwise, deviceAddress is a random device address.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

wifiManager.setDeviceName9+

setDeviceName(devName: string): void

Sets the device name.

System API: This is a system API.

Required permissions: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications)

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
devNamestringYesDevice name to set.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

	import wifiManager from '@ohos.wifiManager';

	try {
		let name = "****";
		wifiManager.setDeviceName(name);	
	}catch(error){
		console.error("failed:" + JSON.stringify(error));
	}

wifiManager.on('wifiStateChange')9+

on(type: "wifiStateChange", callback: Callback<number>): void

Subscribes to WLAN state changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of wifiStateChange.
callbackCallback<number>YesCallback invoked to return the WLAN state.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

WLAN states

ValueDescription
0Deactivated
1Activated
2Activating
3Deactivating

wifiManager.off('wifiStateChange')9+

off(type: "wifiStateChange", callback?: Callback<number>): void

Unsubscribes from WLAN state changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of wifiStateChange.
callbackCallback<number>NoCallback for the WLAN state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

  import wifiManager from '@ohos.wifiManager';
  
  let recvPowerNotifyFunc = (result:number) => {
      console.info("Receive power state change event: " + result);
  }
  
  // Register an event.
  wifiManager.on("wifiStateChange", recvPowerNotifyFunc);
  
  // Unregister an event.
  wifiManager.off("wifiStateChange", recvPowerNotifyFunc);

wifiManager.on('wifiConnectionChange')9+

on(type: "wifiConnectionChange", callback: Callback<number>): void

Subscribes to WLAN connection state changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of wifiConnectionChange.
callbackCallback<number>YesCallback invoked to return the WLAN connection state.

WLAN connection states

ValueDescription
0Disconnected.
1Connected.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

wifiManager.off('wifiConnectionChange')9+

off(type: "wifiConnectionChange", callback?: Callback<number>): void

Unsubscribes from WLAN connection state changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of wifiConnectionChange.
callbackCallback<number>NoCallback for the WLAN connection state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

  import wifiManager from '@ohos.wifiManager';
  
  let recvWifiConnectionChangeFunc = (result:number) => {
      console.info("Receive wifi connection change event: " + result);
  }
  
  // Register an event.
  wifiManager.on("wifiConnectionChange", recvWifiConnectionChangeFunc);
  
  // Unregister an event.
  wifiManager.off("wifiConnectionChange", recvWifiConnectionChangeFunc);

wifiManager.on('wifiScanStateChange')9+

on(type: "wifiScanStateChange", callback: Callback<number>): void

Subscribes to WLAN scan state changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of wifiScanStateChange.
callbackCallback<number>YesCallback invoked to return the WLAN scan state.

WLAN scan states

ValueDescription
0Scan failed.
1Scan successful.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

wifiManager.off('wifiScanStateChange')9+

off(type: "wifiScanStateChange", callback?: Callback<number>): void

Unsubscribes from WLAN scan state changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of wifiScanStateChange.
callbackCallback<number>NoCallback for the WLAN scan state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

  import wifiManager from '@ohos.wifiManager';
  
  let recvWifiScanStateChangeFunc = (result:number) => {
      console.info("Receive Wifi scan state change event: " + result);
  }
  
  // Register an event.
  wifiManager.on("wifiScanStateChange", recvWifiScanStateChangeFunc);
  
  // Unregister an event.
  wifiManager.off("wifiScanStateChange", recvWifiScanStateChangeFunc);

wifiManager.on('wifiRssiChange')9+

on(type: "wifiRssiChange", callback: Callback<number>): void

Subscribes to RSSI changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of wifiRssiChange.
callbackCallback<number>YesCallback invoked to return the RSSI, in dBm.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

wifiManager.off('wifiRssiChange')9+

off(type: "wifiRssiChange", callback?: Callback<number>): void

Unsubscribes from RSSI changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of wifiRssiChange.
callbackCallback<number>NoCallback for the RSSI change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

  import wifiManager from '@ohos.wifiManager';
  
  let recvWifiRssiChangeFunc = (result:number) => {
      console.info("Receive wifi rssi change event: " + result);
  }
  
  // Register an event.
  wifiManager.on("wifiRssiChange", recvWifiRssiChangeFunc);
  
  // Unregister an event.
  wifiManager.off("wifiRssiChange", recvWifiRssiChangeFunc);

wifiManager.on('streamChange')9+

on(type: "streamChange", callback: Callback<number>): void

Subscribes to Wi-Fi stream changes. This API is not supported in the current version, and error code 801 will be thrown.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_WIFI_CONNECTION

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of streamChange.
callbackCallback<number>YesCallback invoked to return the stream change, which can be any of the following values:
- 0: No stream.
- 1: Downward.
- 2: Upward.
- 3: Bidirectional.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

wifiManager.off('streamChange')9+

off(type: "streamChange", callback?: Callback<number>): void

Unsubscribes from Wi-Fi stream changes. This API is not supported in the current version, and error code 801 will be thrown.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_WIFI_CONNECTION

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of streamChange.
callbackCallback<number>NoCallback for the stream change, which can be any of the following values:
- 0: No stream.
- 1: Downward.
- 2: Upward.
- 3: Bidirectional.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

import wifi from '@ohos.wifi';

let recvStreamChangeFunc = (result:number) => {
    console.info("Receive stream change event: " + result);
}

// Register an event.
wifi.on("streamChange", recvStreamChangeFunc);

// Unregister an event.
wifi.off("streamChange", recvStreamChangeFunc);

wifiManager.on('deviceConfigChange')9+

on(type: "deviceConfigChange", callback: Callback<number>): void

Subscribes to Wi-Fi device configuration changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of deviceConfigChange.
callbackCallback<number>YesCallback invoked to return the device configuration change, which can be any of the following values:
- 0: device configuration added.
- 1: device configuration changed.
- 2: device configuration deleted.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

wifiManager.off('deviceConfigChange')9+

off(type: "deviceConfigChange", callback?: Callback<number>): void

Unsubscribes from Wi-Fi device configuration changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.STA

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of deviceConfigChange.
callbackCallback<number>YesCallback for the device configuration change, which can be any of the following values:
- 0: device configuration added.
- 1: device configuration changed.
- 2: device configuration deleted.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

import wifi from '@ohos.wifiManager';

let recvDeviceConfigChangeFunc = (result:number) => {
    console.info("Receive device config change event: " + result);
}

// Register an event.
wifi.on("deviceConfigChange", recvDeviceConfigChangeFunc);

// Unregister an event.
wifi.off("deviceConfigChange", recvDeviceConfigChangeFunc);

wifiManager.on('hotspotStateChange')9+

on(type: "hotspotStateChange", callback: Callback<number>): void

Subscribes to hotspot state changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.AP.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of hotspotStateChange.
callbackCallback<number>YesCallback invoked to return the hotspot state.

Hotspot states

ValueDescription
0Deactivated
1Activated
2Activating
3Deactivating

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2601000Operation failed.

wifiManager.off('hotspotStateChange')9+

off(type: "hotspotStateChange", callback?: Callback<number>): void

Unsubscribes from hotspot state changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.AP.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of hotspotStateChange.
callbackCallback<number>NoCallback for the hotspot state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2601000Operation failed.

Example

  import wifiManager from '@ohos.wifiManager';
  
  let recvHotspotStateChangeFunc = (result:number) => {
      console.info("Receive hotspot state change event: " + result);
  }
  
  // Register an event.
  wifiManager.on("hotspotStateChange", recvHotspotStateChangeFunc);
  
  // Unregister an event.
  wifiManager.off("hotspotStateChange", recvHotspotStateChangeFunc);

wifiManager.on('hotspotStaJoin')9+

on(type: "hotspotStaJoin", callback: Callback<StationInfo>): void

Subscribes to the connection of an STA to a Wi-Fi hotspot.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_WIFI_HOTSPOT

System capability: SystemCapability.Communication.WiFi.AP.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of hotspotStaJoin.
callbackCallback<StationInfo>NoCallback invoked immediately after an STA is connected to a Wi-Fi hotspot.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2601000Operation failed.

wifiManager.off('hotspotStaJoin')9+

off(type: "hotspotStaJoin", callback?: Callback<StationInfo>): void

Unsubscribes from the connection of an STA to a Wi-Fi hotspot.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_WIFI_HOTSPOT

System capability: SystemCapability.Communication.WiFi.AP.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of hotspotStaJoin.
callbackCallback<StationInfo>NoCallback for the connection of an STA to a Wi-Fi hotspot.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2601000Operation failed.

Example

import wifiManager from '@ohos.wifiManager';

let recvHotspotStaJoinFunc = (result:wifiManager.StationInfo) => {
    console.info("Receive hotspot sta join event: " + result);
}

// Register an event.
wifiManager.on("hotspotStaJoin", recvHotspotStaJoinFunc);

// Unregister an event.
wifiManager.off("hotspotStaJoin", recvHotspotStaJoinFunc);

wifiManager.on('hotspotStaLeave')9+

on(type: "hotspotStaLeave", callback: Callback<StationInfo>): void

Subscribes to the disconnection of an STA from a Wi-Fi hotspot.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_WIFI_HOTSPOT

System capability: SystemCapability.Communication.WiFi.AP.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of hotspotStaLeave.
callbackCallback<StationInf]>NoCallback invoked immediately after an STA is disconnected from a Wi-Fi hotspot.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2601000Operation failed.

wifiManager.off('hotspotStaLeave')7+

off(type: "hotspotStaLeave", callback?: Callback<StationInfo>): void

Unsubscribes from the disconnection of an STA from a Wi-Fi hotspot.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_WIFI_HOTSPOT

System capability: SystemCapability.Communication.WiFi.AP.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of hotspotStaLeave.
callbackCallback<StationInf]>YesCallback for the disconnection of an STA from a Wi-Fi hotspot.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2501000Operation failed.

Example

import wifiManager from '@ohos.wifiManager';

let recvHotspotStaLeaveFunc = (result:wifiManager.StationInfo) => {
    console.info("Receive hotspot sta leave event: " + result);
}

// Register an event.
wifiManager.on("hotspotStaLeave", recvHotspotStaLeaveFunc);

// Unregister an event.
wifiManager.off("hotspotStaLeave", recvHotspotStaLeaveFunc);

wifiManager.on('p2pStateChange')9+

on(type: "p2pStateChange", callback: Callback<number>): void

Subscribes to P2P state changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of p2pStateChange.
callbackCallback<number>YesCallback invoked to return the P2P state change.

P2P states

ValueDescription
1Available
2Opening
3Opened
4Closing
5Closed

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

wifiManager.off('p2pStateChange')9+

off(type: "p2pStateChange", callback?: Callback<number>): void

Unsubscribes from P2P state changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of p2pStateChange.
callbackCallback<number>NoCallback for the P2P state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

  import wifiManager from '@ohos.wifiManager';
  
  let recvP2pStateChangeFunc = (result:number) => {
      console.info("Receive p2p state change event: " + result);
  }
  
  // Register an event.
  wifiManager.on("p2pStateChange", recvP2pStateChangeFunc);
  
  // Unregister an event.
  wifiManager.off("p2pStateChange", recvP2pStateChangeFunc);

wifiManager.on('p2pConnectionChange')9+

on(type: "p2pConnectionChange", callback: Callback<WifiP2pLinkedInfo>): void

Subscribes to P2P connection state changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of p2pConnectionChange.
callbackCallback<WifiP2pLinkedInfo>YesCallback invoked to return the P2P connection state change.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

wifiManager.off('p2pConnectionChange')9+

off(type: "p2pConnectionChange", callback?: Callback<WifiP2pLinkedInfo>): void

Unsubscribes from P2P connection state changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of p2pConnectionChange.
callbackCallback<WifiP2pLinkedInfo>NoCallback for the P2P connection state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

  import wifiManager from '@ohos.wifiManager';
  
  let recvP2pConnectionChangeFunc = (result:wifiManager.WifiP2pLinkedInfo) => {
      console.info("Receive p2p connection change event: " + result);
  }
  
  // Register an event.
  wifiManager.on("p2pConnectionChange", recvP2pConnectionChangeFunc);
  
  // Unregister an event.
  wifiManager.off("p2pConnectionChange", recvP2pConnectionChangeFunc);

wifiManager.on('p2pDeviceChange')9+

on(type: "p2pDeviceChange", callback: Callback<WifiP2pDevice>): void

Subscribes to P2P device state changes.

Required permissions:

API version 9: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION

API version 10 and later : ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of p2pDeviceChange.
callbackCallback<WifiP2pDevice>YesCallback invoked to return the device state change.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

wifiManager.off('p2pDeviceChange')9+

off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void

Unsubscribes from P2P device state changes.

Required permissions:

API version 9: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION

API version 10 and later: No permission is required.

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of p2pDeviceChange.
callbackCallback<WifiP2pDevice>NoCallback for the P2P device state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

  import wifiManager from '@ohos.wifiManager';
  
  let recvP2pDeviceChangeFunc = (result:wifiManager.WifiP2pDevice) => {
      console.info("Receive p2p device change event: " + result);
  }
  
  // Register an event.
  wifiManager.on("p2pDeviceChange", recvP2pDeviceChangeFunc);
  
  // Unregister an event.
  wifiManager.off("p2pDeviceChange", recvP2pDeviceChangeFunc);

wifiManager.on('p2pPeerDeviceChange')9+

on(type: "p2pPeerDeviceChange", callback: Callback<WifiP2pDevice[]>): void

Subscribes to P2P peer device state changes.

Required permissions:

API version 9: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.APPROXIMATELY_LOCATION

API version 10 and later : ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of p2pPeerDeviceChange.
callbackCallback<WifiP2pDevice[]>YesCallback invoked to return the P2P peer device state change. If the application has the ohos.permission.GET_WIFI_PEERS_MAC permission, deviceAddress in the return value is a real device address; otherwise, deviceAddress is a random device address.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

wifiManager.off('p2pPeerDeviceChange')9+

off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): void

Unsubscribes from P2P peer device state changes.

Required permissions:

API version 9: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION

API version 10 and later: No permission is required.

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of p2pPeerDeviceChange.
callbackCallback<WifiP2pDevice[]>NoCallback for the P2P peer device state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered. If the application has the ohos.permission.GET_WIFI_PEERS_MAC permission, deviceAddress in the return value is a real device address; otherwise, deviceAddress is a random device address.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

  import wifiManager from '@ohos.wifiManager';
  
  let recvP2pPeerDeviceChangeFunc = (result:wifiManager.WifiP2pDevice[]) => {
      console.info("Receive p2p peer device change event: " + result);
  }
  
  // Register an event.
  wifiManager.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);
  
  // Unregister an event.
  wifiManager.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);

wifiManager.on('p2pPersistentGroupChange')9+

on(type: "p2pPersistentGroupChange", callback: Callback<void>): void

Subscribes to P2P persistent group state changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of p2pPersistentGroupChange.
callbackCallback<void>YesCallback invoked to return the P2P persistent group state change.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

wifiManager.off('p2pPersistentGroupChange')9+

off(type: "p2pPersistentGroupChange", callback?: Callback<void>): void

Unsubscribes from P2P persistent group state changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of p2pPersistentGroupChange.
callbackCallback<void>NoCallback for the P2P persistent group state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

  import wifiManager from '@ohos.wifiManager';
  
  let recvP2pPersistentGroupChangeFunc = (result:void) => {
      console.info("Receive p2p persistent group change event: " + result);
  }
  
  // Register an event.
  wifiManager.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);
  
  // Unregister an event.
  wifiManager.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);

wifiManager.on('p2pDiscoveryChange')9+

on(type: "p2pDiscoveryChange", callback: Callback<number>): void

Subscribes to P2P device discovery state changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of p2pDiscoveryChange.
callbackCallback<number>YesCallback invoked to return the P2P device discovery state change.

P2P discovered device states

ValueDescription
0Initial state.
1Discovered.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

wifiManager.off('p2pDiscoveryChange')9+

off(type: "p2pDiscoveryChange", callback?: Callback<number>): void

Unsubscribes from P2P device discovery state changes.

Required permissions: ohos.permission.GET_WIFI_INFO

System capability: SystemCapability.Communication.WiFi.P2P

Parameters

NameTypeMandatoryDescription
typestringYesEvent type, which has a fixed value of p2pDiscoveryChange.
callbackCallback<number>NoCallback for the P2P device discovery state change. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.

Error codes

For details about the error codes, see Wi-Fi Error Codes.

IDError Message
2801000Operation failed.

Example

  import wifiManager from '@ohos.wifiManager';
  
  let recvP2pDiscoveryChangeFunc = (result:number) => {
      console.info("Receive p2p discovery change event: " + result);
  }
  
  // Register an event.
  wifiManager.on("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc);
  
  // Unregister an event.
  wifiManager.off("p2pDiscoveryChange", recvP2pDiscoveryChangeFunc);

你可能感兴趣的鸿蒙文章

harmony 鸿蒙APIs

harmony 鸿蒙System Common Events (To Be Deprecated Soon)

harmony 鸿蒙System Common Events

harmony 鸿蒙API Reference Document Description

harmony 鸿蒙Enterprise Device Management Overview (for System Applications Only)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager)

harmony 鸿蒙@ohos.distributedBundle (Distributed Bundle Management)

harmony 鸿蒙@ohos.bundle (Bundle)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)

  • 所属分类: 后端技术
  • 本文标签: 鸿蒙 软件
  • 版权声明: 本文链接 https://seaxiang.com/blog/a0d557591fb64a8c8e0e99d3bb1622fa