未验证 提交 e9a844e5 编写于 作者: O openharmony_ci 提交者: Gitee

!12777 [翻译完成】#I662OM

Merge pull request !12777 from Annie_wang/PR12476
...@@ -203,15 +203,16 @@ ...@@ -203,15 +203,16 @@
- [@ohos.data.distributedKVStore](js-apis-distributedKVStore.md) - [@ohos.data.distributedKVStore](js-apis-distributedKVStore.md)
- [@ohos.data.preferences](js-apis-data-preferences.md) - [@ohos.data.preferences](js-apis-data-preferences.md)
- [@ohos.data.rdb](js-apis-data-rdb.md) - [@ohos.data.rdb](js-apis-data-rdb.md)
- [@ohos.data.ValuesBucket](js-apis-data-ValuesBucket.md) - [@ohos.data.ValuesBucket](js-apis-data-valuesBucket.md)
- data/rdb/[resultSet](js-apis-data-resultset.md) - data/rdb
- [resultSet](js-apis-data-resultset.md)
- File Management - File Management
- [@ohos.document](js-apis-document.md) - [@ohos.document](js-apis-document.md)
- [@ohos.environment](js-apis-environment.md) - [@ohos.environment](js-apis-environment.md)
- [@ohos.data.fileAccess](js-apis-fileAccess.md) - [@ohos.data.fileAccess](js-apis-fileAccess.md)
- [@ohos.fileExtensionInfo](js-apis-fileExtensionInfo.md) - [@ohos.fileExtensionInfo](js-apis-fileExtensionInfo.md)
- [@ohos.fileio](js-apis-fileio.md) - [@ohos.fileio](js-apis-fileio.md)
- [@ohos.filemanagement.userfile_manager](js-apis-userfilemanager.md) - [@ohos.filemanagement.userFileManager](js-apis-userfilemanager.md)
- [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md)
- [@ohos.securityLabel](js-apis-securityLabel.md) - [@ohos.securityLabel](js-apis-securityLabel.md)
- [@ohos.statfs](js-apis-statfs.md) - [@ohos.statfs](js-apis-statfs.md)
...@@ -240,10 +241,13 @@ ...@@ -240,10 +241,13 @@
- [@ohos.nfc.controller](js-apis-nfcController.md) - [@ohos.nfc.controller](js-apis-nfcController.md)
- [@ohos.nfc.tag](js-apis-nfcTag.md) - [@ohos.nfc.tag](js-apis-nfcTag.md)
- [@ohos.rpc](js-apis-rpc.md) - [@ohos.rpc](js-apis-rpc.md)
- [@ohos.wifiManager (WLAN)](js-apis-wifiManager.md)
- [@ohos.wifiManagerExt](js-apis-wifiManagerExt.md)
- [@ohos.wifi](js-apis-wifi.md) - [@ohos.wifi](js-apis-wifi.md)
- [@ohos.wifiext](js-apis-wifiext.md) - [@ohos.wifiext](js-apis-wifiext.md)
- tag/[nfctech](js-apis-nfctech.md) - tag
- tag/[tagSession](js-apis-tagSession.md) - [nfctech](js-apis-nfctech.md)
- [tagSession](js-apis-tagSession.md)
- Basic Features - Basic Features
- [@ohos.accessibility](js-apis-accessibility.md) - [@ohos.accessibility](js-apis-accessibility.md)
- [@ohos.accessibility.config](js-apis-accessibility-config.md) - [@ohos.accessibility.config](js-apis-accessibility-config.md)
......
# App Account Management # @ohos.account.appAccount
The **appAccount** module provides APIs for adding, deleting, modifying, and querying app account information, and supports inter-app authentication and distributed data synchronization. The **appAccount** module provides APIs for adding, deleting, modifying, and querying app account information, and supports inter-app authentication and distributed data synchronization.
...@@ -3173,7 +3173,7 @@ Set credentials for an app account. This API uses an asynchronous callback to re ...@@ -3173,7 +3173,7 @@ Set credentials for an app account. This API uses an asynchronous callback to re
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------- | ------------------------- | ---- | ------------- | | -------------- | ------------------------- | ---- | ------------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| credentialType | string | Yes | Type of the credential to delete. | | credentialType | string | Yes | Type of the credential to set. |
| credential | string | Yes | Credential value. | | credential | string | Yes | Credential value. |
| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.|
...@@ -3203,7 +3203,7 @@ Set credentials for an app account. This API uses a promise to return the result ...@@ -3203,7 +3203,7 @@ Set credentials for an app account. This API uses a promise to return the result
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------- | ------ | ---- | ---------- | | -------------- | ------ | ---- | ---------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| credentialType | string | Yes | Type of the credential to delete.| | credentialType | string | Yes | Type of the credential to set.|
| credential | string | Yes | Credential value.| | credential | string | Yes | Credential value.|
**Return value** **Return value**
...@@ -3576,7 +3576,7 @@ Obtains the credential of an app account. This API uses an asynchronous callback ...@@ -3576,7 +3576,7 @@ Obtains the credential of an app account. This API uses an asynchronous callback
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------- | --------------------------- | ---- | -------------- | | -------------- | --------------------------- | ---- | -------------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| credentialType | string | Yes | Type of the credential to delete.| | credentialType | string | Yes | Type of the credential to obtain.|
| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the credential obtained. Otherwise, **err** is an error object.| | callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the credential obtained. Otherwise, **err** is an error object.|
**Example** **Example**
...@@ -3606,7 +3606,7 @@ Obtains the credential of an app account. This API uses a promise to return the ...@@ -3606,7 +3606,7 @@ Obtains the credential of an app account. This API uses a promise to return the
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------- | ------ | ---- | ---------- | | -------------- | ------ | ---- | ---------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| credentialType | string | Yes | Type of the credential to delete.| | credentialType | string | Yes | Type of the credential to obtain.|
**Return value** **Return value**
......
# Bluetooth # @ohos.bluetooth
The **Bluetooth** module provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. The **Bluetooth** module provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising.
> **NOTE**<br> > **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -202,7 +203,7 @@ Obtains the connection state of a profile. ...@@ -202,7 +203,7 @@ Obtains the connection state of a profile.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | --------- | ---- | ------------------------------------- | | --------- | --------- | ---- | ------------------------------------- |
| ProfileId | profileId | Yes | ID of the target profile, for example, **PROFILE_A2DP_SOURCE**.| | ProfileId | profileId | Yes | ID of the profile to obtain, for example, **PROFILE_A2DP_SOURCE**.|
**Return value** **Return value**
...@@ -1280,10 +1281,6 @@ Obtains the connected devices. ...@@ -1280,10 +1281,6 @@ Obtains the connected devices.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
**Parameters**
No value is returned.
**Return value** **Return value**
| Type | Description | | Type | Description |
...@@ -2695,8 +2692,6 @@ Obtains all services of the remote BLE device. This API uses a promise to return ...@@ -2695,8 +2692,6 @@ Obtains all services of the remote BLE device. This API uses a promise to return
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
**Parameters**
**Return value** **Return value**
| Type | Description | | Type | Description |
...@@ -2830,7 +2825,7 @@ Reads the descriptor contained in the specific characteristic of the remote BLE ...@@ -2830,7 +2825,7 @@ Reads the descriptor contained in the specific characteristic of the remote BLE
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ---------------------------------------- | ---- | ----------------------- | | ---------- | ---------------------------------------- | ---- | ----------------------- |
| descriptor | [BLEDescriptor](#bledescriptor) | Yes | Descriptor to read. | | descriptor | [BLEDescriptor](#bledescriptor) | Yes | Descriptor to read. |
| callback | AsyncCallback&lt;[BLECharacteristic](#blecharacteristic)&gt; | Yes | Callback invoked to return the descriptor read.| | callback | AsyncCallback&lt;[BLEDescriptor](#bledescriptor)&gt; | Yes | Callback invoked to return the descriptor read.|
**Return value** **Return value**
...@@ -3309,7 +3304,7 @@ Enumerates the scan modes. ...@@ -3309,7 +3304,7 @@ Enumerates the scan modes.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description | | Name | Value | Description |
| ---------------------------------------- | ---- | --------------- | | ---------------------------------------- | ---- | --------------- |
| SCAN_MODE_NONE | 0 | No scan mode. | | SCAN_MODE_NONE | 0 | No scan mode. |
| SCAN_MODE_CONNECTABLE | 1 | Connectable mode. | | SCAN_MODE_CONNECTABLE | 1 | Connectable mode. |
...@@ -3324,7 +3319,7 @@ Enumerates the pairing states. ...@@ -3324,7 +3319,7 @@ Enumerates the pairing states.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description | | Name | Value | Description |
| ------------------ | ---- | ------ | | ------------------ | ---- | ------ |
| BOND_STATE_INVALID | 0 | Invalid pairing.| | BOND_STATE_INVALID | 0 | Invalid pairing.|
| BOND_STATE_BONDING | 1 | Pairing. | | BOND_STATE_BONDING | 1 | Pairing. |
...@@ -3350,7 +3345,7 @@ Enumerates the SPP link types. ...@@ -3350,7 +3345,7 @@ Enumerates the SPP link types.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description | | Name | Value | Description |
| ---------- | ---- | ------------- | | ---------- | ---- | ------------- |
| SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link type.| | SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link type.|
...@@ -3510,7 +3505,7 @@ Enumerates the profile connection states. ...@@ -3510,7 +3505,7 @@ Enumerates the profile connection states.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description | | Name | Value | Description |
| ------------------- | ---- | -------------- | | ------------------- | ---- | -------------- |
| STATE_DISCONNECTED | 0 | Disconnected. | | STATE_DISCONNECTED | 0 | Disconnected. |
| STATE_CONNECTING | 1 | Connecting.| | STATE_CONNECTING | 1 | Connecting.|
...@@ -3558,7 +3553,7 @@ Enumerates the scan duty options. ...@@ -3558,7 +3553,7 @@ Enumerates the scan duty options.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description | | Name | Value | Description |
| --------------------- | ---- | ------------ | | --------------------- | ---- | ------------ |
| SCAN_MODE_LOW_POWER | 0 | Low-power mode, which is the default value.| | SCAN_MODE_LOW_POWER | 0 | Low-power mode, which is the default value.|
| SCAN_MODE_BALANCED | 1 | Balanced mode. | | SCAN_MODE_BALANCED | 1 | Balanced mode. |
...@@ -3571,7 +3566,7 @@ Enumerates the hardware match modes of BLE scan filters. ...@@ -3571,7 +3566,7 @@ Enumerates the hardware match modes of BLE scan filters.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description | | Name | Value | Description |
| --------------------- | ---- | ---------------------------------------- | | --------------------- | ---- | ---------------------------------------- |
| MATCH_MODE_AGGRESSIVE | 1 | Hardware reports the scan result with a lower threshold of signal strength and few number of matches in a duration. This is the default value.| | MATCH_MODE_AGGRESSIVE | 1 | Hardware reports the scan result with a lower threshold of signal strength and few number of matches in a duration. This is the default value.|
| MATCH_MODE_STICKY | 2 | Hardware reports the scan result with a higher threshold of signal strength and sightings. | | MATCH_MODE_STICKY | 2 | Hardware reports the scan result with a higher threshold of signal strength and sightings. |
...@@ -3596,7 +3591,7 @@ Enumerates the Bluetooth states. ...@@ -3596,7 +3591,7 @@ Enumerates the Bluetooth states.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description | | Name | Value | Description |
| --------------------- | ---- | ------------------ | | --------------------- | ---- | ------------------ |
| STATE_OFF | 0 | Bluetooth is turned off. | | STATE_OFF | 0 | Bluetooth is turned off. |
| STATE_TURNING_ON | 1 | Bluetooth is being turned on. | | STATE_TURNING_ON | 1 | Bluetooth is being turned on. |
...@@ -3641,7 +3636,7 @@ Defines the content of a BLE advertisement packet. ...@@ -3641,7 +3636,7 @@ Defines the content of a BLE advertisement packet.
| Name | Type | Readable | Writable | Description | | Name | Type | Readable | Writable | Description |
| ---------------- | ------------------- | ---- | ---- | ------------------ | | ---------------- | ------------------- | ---- | ---- | ------------------ |
| manufactureId | Array&lt;string&gt; | Yes | Yes | Manufacturer ID allocated by the Bluetooth SIG.| | manufactureId | number | Yes | Yes | Manufacturer ID allocated by the Bluetooth SIG.|
| manufactureValue | ArrayBuffer | Yes | Yes | Manufacturer data. | | manufactureValue | ArrayBuffer | Yes | Yes | Manufacturer data. |
...@@ -3713,7 +3708,7 @@ Enumerates the major classes of Bluetooth devices. ...@@ -3713,7 +3708,7 @@ Enumerates the major classes of Bluetooth devices.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description | | Name | Value | Description |
| ------------------- | ------ | ---------- | | ------------------- | ------ | ---------- |
| MAJOR_MISC | 0x0000 | Miscellaneous device. | | MAJOR_MISC | 0x0000 | Miscellaneous device. |
| MAJOR_COMPUTER | 0x0100 | Computer. | | MAJOR_COMPUTER | 0x0100 | Computer. |
...@@ -3734,7 +3729,7 @@ Enumerates the major and minor classes of Bluetooth devices. ...@@ -3734,7 +3729,7 @@ Enumerates the major and minor classes of Bluetooth devices.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description | | Name | Value | Description |
| ---------------------------------------- | ------ | --------------- | | ---------------------------------------- | ------ | --------------- |
| COMPUTER_UNCATEGORIZED | 0x0100 | Unclassified computer. | | COMPUTER_UNCATEGORIZED | 0x0100 | Unclassified computer. |
| COMPUTER_DESKTOP | 0x0104 | Desktop computer. | | COMPUTER_DESKTOP | 0x0104 | Desktop computer. |
...@@ -3830,7 +3825,7 @@ Enumerates the A2DP playing states. ...@@ -3830,7 +3825,7 @@ Enumerates the A2DP playing states.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description | | Name | Value | Description |
| ----------------- | ------ | ------- | | ----------------- | ------ | ------- |
| STATE_NOT_PLAYING | 0x0000 | Not playing. | | STATE_NOT_PLAYING | 0x0000 | Not playing. |
| STATE_PLAYING | 0x0001 | Playing.| | STATE_PLAYING | 0x0001 | Playing.|
...@@ -3842,9 +3837,9 @@ Enumerates the Bluetooth profiles. API version 9 is added with **PROFILE_HID_HOS ...@@ -3842,9 +3837,9 @@ Enumerates the Bluetooth profiles. API version 9 is added with **PROFILE_HID_HOS
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description | | Name | Value | Description |
| -------------------------------- | ------ | --------------- | | -------------------------------- | ------ | --------------- |
| PROFILE_A2DP_SOURCE | 0x0001 | A2DP profile.| | PROFILE_A2DP_SOURCE | 1 | A2DP profile.|
| PROFILE_HANDS_FREE_AUDIO_GATEWAY | 0x0004 | HFP profile. | | PROFILE_HANDS_FREE_AUDIO_GATEWAY | 4 | HFP profile. |
| PROFILE_HID_HOST<sup>9+</sup> | 0x0006 | Human Interface Device (HID) profile. | | PROFILE_HID_HOST<sup>9+</sup> | 6 | Human Interface Device (HID) profile. |
| PROFILE_PAN_NETWORK<sup>9+</sup> | 0x0007 | PAN profile. | | PROFILE_PAN_NETWORK<sup>9+</sup> | 7 | PAN profile. |
# Standard NFC Card Emulation # @ohos.nfc.cardEmulation
The **cardEmulation** module implements Near-Field Communication (NFC) card emulation. You can use the APIs provided by this module to determine the card emulation type supported and implement Host-based Card Emulation (HCE). The **cardEmulation** module implements Near-Field Communication (NFC) card emulation. You can use the APIs provided by this module to determine the card emulation type supported and implement Host-based Card Emulation (HCE).
> **NOTE**<br> > **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. > 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 ## Modules to Import
``` ```
...@@ -18,7 +18,7 @@ Enumerates the NFC card emulation types. ...@@ -18,7 +18,7 @@ Enumerates the NFC card emulation types.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
| Name| Default Value| Description| | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| HCE | 0 | HCE.| | HCE | 0 | HCE.|
| UICC | 1 | Subscriber identity module (SIM) card emulation.| | UICC | 1 | Subscriber identity module (SIM) card emulation.|
...@@ -30,8 +30,6 @@ isSupported(feature: number): boolean ...@@ -30,8 +30,6 @@ isSupported(feature: number): boolean
Checks whether a certain type of card emulation is supported. Checks whether a certain type of card emulation is supported.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
...@@ -42,9 +40,9 @@ Checks whether a certain type of card emulation is supported. ...@@ -42,9 +40,9 @@ Checks whether a certain type of card emulation is supported.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.| | boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.|
## HceService<sup>8+</sup> ## HceService<sup>8+</sup>
......
# Active Tag # @ohos.connectedTag
The **connectedTag** module provides methods for using active tags. You can use the APIs provided by this module to initialize the active tag chip and read and write active tags. The **connectedTag** module provides APIs for using active tags. You can use the APIs to initialize the active tag chip and read and write active tags.
> **NOTE**<br> > **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
``` ```js
import connectedTag from '@ohos.connectedTag'; import connectedTag from '@ohos.connectedTag';
``` ```
## connectedTag.init ## connectedTag.init
init(): boolean init(): boolean
...@@ -23,11 +22,11 @@ Initializes the active tag chip. ...@@ -23,11 +22,11 @@ Initializes the active tag chip.
**System capability**: SystemCapability.Communication.ConnectedTag **System capability**: SystemCapability.Communication.ConnectedTag
- Return value **Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the initialization is successful; returns **false** otherwise.|
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## connectedTag.uninit ## connectedTag.uninit
...@@ -39,125 +38,136 @@ Uninitializes the active tag resources. ...@@ -39,125 +38,136 @@ Uninitializes the active tag resources.
**System capability**: SystemCapability.Communication.ConnectedTag **System capability**: SystemCapability.Communication.ConnectedTag
- Return value **Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## connectedTag.readNdefTag ## connectedTag.readNdefTag
readNdefTag(): Promise&lt;string&gt; readNdefTag(): Promise&lt;string&gt;
Reads the content of this active tag. This method uses a promise to return the result. Reads the content of this active tag. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.ConnectedTag **System capability**: SystemCapability.Communication.ConnectedTag
- Return value **Return value**
| **Type**| **Description**|
| -------- | -------- |
| Promise&lt;string&gt; | Promise used to return the content of the active tag.|
- Example | **Type**| **Description**|
``` | -------- | -------- |
import connectedTag from '@ohos.connectedTag'; | Promise&lt;string&gt; | Promise used to return the content of the active tag.|
connectedTag.readNdefTag().then(result => { **Example**
console.log("promise recv ndef response: " + result);
}); ```js
``` import connectedTag from '@ohos.connectedTag';
connectedTag.readNdefTag().then((data) => {
console.log("connectedTag readNdefTag Promise data = " + data);
}).catch((err)=> {
console.log("connectedTag readNdefTag Promise err: " + err);
});
```
## connectedTag.readNdefTag ## connectedTag.readNdefTag
readNdefTag(callback: AsyncCallback&lt;string&gt;): void readNdefTag(callback: AsyncCallback&lt;string&gt;): void
Reads the content of this active tag. This method uses an asynchronous callback to return the result. Reads the content of this active tag. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.ConnectedTag **System capability**: SystemCapability.Communication.ConnectedTag
- Parameters **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | **Name**| **Type**| **Mandatory**| **Description**|
| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the active tag content obtained.| | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the active tag content obtained.|
**Example**
- Example ```js
``` import connectedTag from '@ohos.connectedTag';
import connectedTag from '@ohos.connectedTag';
connectedTag.readNdefTag(result => { connectedTag.readNdefTag((err, data)=> {
console.log("callback recv ndef response: " + result); if (err) {
}); console.log("connectedTag readNdefTag AsyncCallback err: " + err);
``` } else {
console.log("connectedTag readNdefTag AsyncCallback data: " + data);
}
});
```
## connectedTag.writeNdefTag ## connectedTag.writeNdefTag
writeNdefTag(data: string): Promise&lt;void&gt; writeNdefTag(data: string): Promise&lt;void&gt;
Writes data to this active tag. This method uses a promise to return the result. Writes data to this active tag. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.ConnectedTag **System capability**: SystemCapability.Communication.ConnectedTag
- Parameters **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | **Name**| **Type**| **Mandatory**| **Description**|
| data | string | Yes| Data to write. The maximum length is 1024 bytes.| | -------- | -------- | -------- | -------- |
| data | string | Yes| Data to write. The maximum length is 1024 bytes.|
- Return value
| **Type**| **Description**| **Return value**
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result. This method returns no value.| | **Type**| **Description**|
| -------- | -------- |
- Example | Promise&lt;void&gt; | Promise that returns no value.|
```
import connectedTag from '@ohos.connectedTag'; **Example**
writeNdefTag.write("010203") ```js
.then((value) => { import connectedTag from '@ohos.connectedTag';
// Data is written to the tag.
console.log(`success to write event: ${value}`); var rawData = "010203"; // change it tobe correct.
}).catch((err) => { connectedTag.writeNdefTag(rawData).then(() => {
// Failed to write data to the tag. console.log("connectedTag writeNdefTag Promise success.");
console.error(`failed to write event because ${err.code}`); }).catch((err)=> {
}); console.log("connectedTag writeNdefTag Promise err: " + err);
``` });
```
## connectedTag.writeNdefTag ## connectedTag.writeNdefTag
writeNdefTag(data: string, callback: AsyncCallback&lt;void&gt;): void writeNdefTag(data: string, callback: AsyncCallback&lt;void&gt;): void
Writes data to this active tag. This method uses an asynchronous callback to return the result. Writes data to this active tag. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.ConnectedTag **System capability**: SystemCapability.Communication.ConnectedTag
- Parameters **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| data | string | Yes| Data to write. The maximum length is 1024 bytes.|
| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the active tag content obtained.|
- Example | **Name**| **Type**| **Mandatory**| **Description**|
``` | -------- | -------- | -------- | -------- |
import connectedTag from '@ohos.connectedTag'; | data | string | Yes| Data to write. The maximum length is 1024 bytes.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the active tag content obtained.|
connectedTag.writeNdefTag("010203", (err, value) => { **Example**
```js
import connectedTag from '@ohos.connectedTag';
var rawData = "010203"; // change it tobe correct.
connectedTag.writeNdefTag(rawData, (err)=> {
if (err) { if (err) {
// Failed to write data to the tag. console.log("connectedTag writeNdefTag AsyncCallback err: " + err);
console.error(`failed to write event because ${err.code}`); } else {
return; console.log("connectedTag writeNdefTag AsyncCallback success.");
} }
});
// Data is written to the tag. ```
console.log(`success to write event: ${value}`);
});
```
## connectedTag.on('notify') ## connectedTag.on('notify')
...@@ -169,18 +179,12 @@ Registers the NFC field strength state events. ...@@ -169,18 +179,12 @@ Registers the NFC field strength state events.
**System capability**: SystemCapability.Communication.ConnectedTag **System capability**: SystemCapability.Communication.ConnectedTag
- Parameters **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **notify**.|
| callback | Callback&lt;number&gt; | Yes| Callback invoked to return the field strength state.|
- Enumerates the field strength states.
| **Value**| **Description**|
| -------- | -------- |
| 0 | Field off.|
| 1 | Field on.|
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **notify**.|
| callback | Callback&lt;number&gt; | Yes| Callback used to return the [NfcRfType](#nfcrftype).|
## connectedTag.off('notify') ## connectedTag.off('notify')
...@@ -192,36 +196,54 @@ Unregisters the NFC field strength state events. ...@@ -192,36 +196,54 @@ Unregisters the NFC field strength state events.
**System capability**: SystemCapability.Communication.ConnectedTag **System capability**: SystemCapability.Communication.ConnectedTag
- Parameters **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **notify**.|
| callback | Callback&lt;number&gt; | No| Callback used to return the field strength state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
- Example | **Name**| **Type**| **Mandatory**| **Description**|
``` | -------- | -------- | -------- | -------- |
import connectedTag from '@ohos.connectedTag'; | type | string | Yes| Event type. The value is **notify**.|
| callback | Callback&lt;number&gt; | No| Callback used to return the field strength state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
var NFC_RF_NOTIFY = "notify"; **Example**
var recvNfcRfNotifyFunc = result => { ```js
console.info("nfc rf receive state: " + result); import connectedTag from '@ohos.connectedTag';
// Register the event.
connectedTag.on("notify", (err, rfState)=> {
if (err) {
console.log("connectedTag on Callback err: " + err);
} else {
console.log("connectedTag on Callback rfState: " + rfState);
} }
});
var initStatus = connectedTag.init();
console.log("connectedTag init status: " + initStatus);
// Register event notification. // Add nfc connecected tag business oprations here...
connectedTag.on(NFC_RF_NOTIFY, recvNfcRfNotifyFunc); // connectedTag.writeNdefTag(rawData)
// connectedTag.readNdefTag()
// Unregister event notification. var uninitStatus = connectedTag.uninit();
connectedTag.off(NFC_RF_NOTIFY, recvNfcRfNotifyFunc); console.log("connectedTag uninit status: " + uninitStatus);
```
// Unregister the event.
connectedTag.off("notify", (err, rfState)=> {
if (err) {
console.log("connectedTag off Callback err: " + err);
} else {
console.log("connectedTag off Callback rfState: " + rfState);
}
});
```
## NfcRfType ## NfcRfType
Enumerates the NFC states. Enumerates the NFC field strength states.
**System capability**: SystemCapability.Communication.ConnectedTag **System capability**: SystemCapability.Communication.ConnectedTag
| Name| Default Value| Description| | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| NFC_RF_LEAVE | 0 | Field on.| | NFC_RF_LEAVE | 0 | Field off.|
| NFC_RF_ENTER | 1 | Field on.| | NFC_RF_ENTER | 1 | Field on.|
# Value Bucket # @ohos.data.ValuesBucket
The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to insert data into a database. The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to insert data into a database.
......
# Distributed Account Management # @ohos.account.distributedAccount
The **distributedAccount** module provides APIs for managing distributed accounts, including querying and updating account login status. The **distributedAccount** module provides APIs for managing distributed accounts, including querying and updating account login states.
> **NOTE**<br> > **NOTE**
> >
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -49,7 +49,7 @@ Obtains distributed account information. This API uses an asynchronous callback ...@@ -49,7 +49,7 @@ Obtains distributed account information. This API uses an asynchronous callback
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[DistributedInfo](#distributedinfo)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and data is the distributed account information obtained. Otherwise, **err** is an error object.| | callback | AsyncCallback&lt;[DistributedInfo](#distributedinfo)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the distributed account information obtained. Otherwise, **err** is an error object.|
**Error codes** **Error codes**
...@@ -124,7 +124,7 @@ Obtains distributed account information. This API uses an asynchronous callback ...@@ -124,7 +124,7 @@ Obtains distributed account information. This API uses an asynchronous callback
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[DistributedInfo](#distributedinfo)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and data is the distributed account information obtained. Otherwise, **err** is an error object.| | callback | AsyncCallback&lt;[DistributedInfo](#distributedinfo)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the distributed account information obtained. Otherwise, **err** is an error object.|
**Example** **Example**
```js ```js
...@@ -181,7 +181,7 @@ Sets the distributed account information. This API uses an asynchronous callback ...@@ -181,7 +181,7 @@ Sets the distributed account information. This API uses an asynchronous callback
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| accountInfo | [DistributedInfo](#distributedinfo) | Yes| New distributed account information.| | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to set.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result. If the distributed account information is set successfully, **err** is **undefined**. Otherwise, **err** is an error object.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result. If the distributed account information is set successfully, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes** **Error codes**
...@@ -219,7 +219,7 @@ Sets the distributed account information. This API uses a promise to return the ...@@ -219,7 +219,7 @@ Sets the distributed account information. This API uses a promise to return the
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| accountInfo | [DistributedInfo](#distributedinfo) | Yes| New distributed account information.| | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to set.|
**Return value** **Return value**
...@@ -322,7 +322,7 @@ Defines distributed OS account information. ...@@ -322,7 +322,7 @@ Defines distributed OS account information.
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes| Name of the distributed account. It must be a non-null string.| | name | string | Yes| Name of the distributed account. It must be a non-null string.|
| id | string | Yes| UID of the distributed account. It must be a non-null string.| | id | string | Yes| UID of the distributed account. It must be a non-null string.|
| event | string | Yes| Login state of a distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:<br>-&nbsp;Ohos.account.event.LOGIN<br>-&nbsp;Ohos.account.event.LOGOUT<br>-&nbsp;Ohos.account.event.TOKEN_INVALID<br>-&nbsp;Ohos.account.event.LOGOFF | | event | string | Yes| Login state of the distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:<br>-&nbsp;Ohos.account.event.LOGIN<br>-&nbsp;Ohos.account.event.LOGOUT<br>-&nbsp;Ohos.account.event.TOKEN_INVALID<br>-&nbsp;Ohos.account.event.LOGOFF |
| nickname<sup>9+</sup> | string | No| Nickname of the distributed account. It must be a non-null string.| | nickname<sup>9+</sup> | string | No| Nickname of the distributed account. It must be a non-null string.|
| avatar<sup>9+</sup> | string | No| Avatar of the distributed account. It must be a non-null string.| | avatar<sup>9+</sup> | string | No| Avatar of the distributed account. It must be a non-null string.|
| scalableData | object | No| Extended information about the distributed account, passed in key-value (KV) pairs.<br>**NOTE**<br>This parameter is reserved and not used in query and update methods.| | scalableData | object | No| Extended information about the distributed account, passed in key-value (KV) pairs.<br>**NOTE**<br>This parameter is reserved and not used in the setters and getters.|
# NFC Tags # @ohos.nfc.tag
The **nfcTag** module provides APIs for managing Near-Field Communication (NFC) tags. The **nfcTag** module provides APIs for managing Near-Field Communication (NFC) tags.
> **NOTE**<br> > **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## **Declaration** ## **Declaration**
...@@ -47,12 +48,10 @@ Before developing applications related to tag read and write, you must declare N ...@@ -47,12 +48,10 @@ Before developing applications related to tag read and write, you must declare N
} }
``` ```
> **CAUTION**<br> > **CAUTION**<br>
> 1. The **actions** field is mandatory. It must be **ohos.nfc.tag.action.TAG_FOUND** and cannot be changed.
> - The **actions** field is mandatory. It must be **ohos.nfc.tag.action.TAG_FOUND** and cannot be changed. 2. The **name** field under **metadata** is mandatory. It must be **tag-tech** and cannot be changed.
> - The **name** field of **metadata** is mandatory. It must be **tag-tech** and cannot be changed. 3. The **value** field under **metadata** is mandatory. It can be **NfcA**, **NfcB**, **NfcF**, **NfcV**, **IsoDep**, **Ndef**, **MifareClassic**, **MifareUL**, **NdefFormatable** or any of their combinations. Incorrect settings of this field will cause a parsing failure.
> - The **value** field of **metadata** is mandatory. It can be **NfcA**, **NfcB**, **NfcF**, **NfcV**, **IsoDep**, **Ndef**, **MifareClassic**, **MifareUL**, **NdefFormatable** or their combinations. Incorrect setting of this field will cause a parsing failure. 4. The **name** field under **requestPermissions** is mandatory. It must be **ohos.permission.NFC_TAG** and cannot be changed.
> - The **name** field of **requestPermissions** is mandatory. It must be **ohos.permission.NFC_TAG** and cannot be changed.
## **Modules to Import** ## **Modules to Import**
...@@ -61,34 +60,63 @@ import tag from '@ohos.nfc.tag'; ...@@ -61,34 +60,63 @@ import tag from '@ohos.nfc.tag';
``` ```
## **tag.TagInfo** ## **tag.TagInfo**
Before reading or writing data to a card with tags, the application must obtain **TagInfo** to determine the tag technologies supported by the card. Then, the application can invoke the correct API to communicate with the card.
Before a card with tags is read or written, **TagInfo** must be obtained to determine the tag technologies supported by the card. In this way, the application can invoke the correct API to communicate with the card.
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
onCreate(want, launchParam) { onCreate(want, launchParam) {
// Add other code here. // Add other code here.
// want is initialized by the NFC service and contains taginfo. // want is initialized by the NFC service and contains tagInfo.
var tagInfo = tag.getTagInfo(want); var tagInfo;
if (tagInfo == undefined) { try {
tagInfo = tag.getTagInfo(want);
} catch (error) {
console.log("tag.getTagInfo catched error: " + error);
}
if (tagInfo == null || tagInfo == undefined) {
console.log("no TagInfo to be created, ignore it."); console.log("no TagInfo to be created, ignore it.");
return; return;
} }
// get the supported technologies for this found tag.
var isNfcATag = false; var isNfcATag = false;
var isIsoDepTag = false;
for (var i = 0; i < tagInfo.technology.length; i++) { for (var i = 0; i < tagInfo.technology.length; i++) {
if (tagInfo.technology[i] == tag.NFC_A) { if (tagInfo.technology[i] == tag.NFC_A) {
isNfcATag = true; isNfcATag = true;
break; }
if (tagInfo.technology[i] == tag.ISO_DEP) {
isIsoDepTag = true;
} }
// Also check for technology tag.NFC_B, NFC_F, NFC_V, ISO_DEP, NDEF, MIFARE_CLASSIC, MIFARE_ULTRALIGHT, and NDEF_FORMATABLE. // Also check for technology tag.NFC_B, NFC_F, NFC_V, ISO_DEP, NDEF, MIFARE_CLASSIC, MIFARE_ULTRALIGHT, and NDEF_FORMATABLE.
} }
// use NfcA APIs to access the found tag.
if (isNfcATag) { if (isNfcATag) {
var nfcA = tag.getNfcATag(taginfo); var nfcA;
try {
nfcA = tag.getNfcATag(taginfo);
} catch (error) {
console.log("tag.getNfcATag catched error: " + error);
}
// Other code to read or write this tag.
}
// use getIsoDep APIs to access the found tag.
if (isIsoDepTag) {
var isoDep;
try {
isoDep = tag.getIsoDep(taginfo);
} catch (error) {
console.log("tag.getIsoDep catched error: " + error);
}
// Other code to read or write this tag. // Other code to read or write this tag.
} }
// use the same code to handle "NfcA/NfcB/NfcF/NfcV/IsoDep/Ndef/MifareClassic/MifareUL/NdefFormatable", such as, // Use the same code to handle "NfcA/NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable".
// var isoDep = tag.getIsoDepTag(taginfo);
} }
``` ```
...@@ -156,78 +184,122 @@ Obtains an **NfcVTag** object, which allows access to the tags that use the NFC- ...@@ -156,78 +184,122 @@ Obtains an **NfcVTag** object, which allows access to the tags that use the NFC-
| -------- | ---------------- | | -------- | ---------------- |
| [NfcVTag](js-apis-nfctech.md#nfcvtag) | **NfcVTag** object obtained.| | [NfcVTag](js-apis-nfctech.md#nfcvtag) | **NfcVTag** object obtained.|
## tag.getIsoDepTag<sup>9+</sup> ## tag.getIsoDep<sup>9+</sup>
getIsoDepTag(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTag9 ) getIsoDep(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTag9 )
Obtains an **IsoDepTag** object, which allows access to the tags that use the ISO-DEP technology. Obtains an **IsoDepTag** object, which allows access to the tags that use the ISO-DEP technology.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. |
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| ---------- | ------------------| | ---------- | ------------------|
| [IsoDepTag](js-apis-nfctech.md#isodeptag9) | **IsoDepTag** object obtained.| | [IsoDepTag](js-apis-nfctech.md#isodeptag9) | **IsoDepTag** object obtained.|
## tag.getNdefTag<sup>9+</sup> **Error codes**
getNdefTag(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9) For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
Obtains an **NdefTag** object, which allows access to the tags in the NFC Data Exchange Format (NDEF). | ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
## tag.getNdef<sup>9+</sup>
**Required permissions**: ohos.permission.NFC_TAG getNdef(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9)
Obtains an **NdefTag** object, which allows access to the tags in the NFC Data Exchange Format (NDEF).
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. |
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| ---------| -------------- | | ---------| -------------- |
| [NdefTag](js-apis-nfctech.md#ndeftag9) | **NdefTag** object obtained.| | [NdefTag](js-apis-nfctech.md#ndeftag9) | **NdefTag** object obtained.|
## tag.getMifareClassicTag<sup>9+</sup> **Error codes**
getMifareClassicTag(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
Obtains a **MifareClassicTag** object, which allows access to the tags that use MIFARE Classic. | ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Required permissions**: ohos.permission.NFC_TAG ## tag.getMifareClassic<sup>9+</sup>
getMifareClassic(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9)
Obtains a **MifareClassicTag** object, which allows access to the tags that use MIFARE Classic.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. |
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| ----------------- | ------------------------| | ----------------- | ------------------------|
| [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) | **MifareClassicTag** object obtained.| | [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) | **MifareClassicTag** object obtained.|
## tag.getMifareUltralightTag<sup>9+</sup> **Error codes**
getMifareUltralightTag(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
Obtains a **MifareUltralightTag** object, which allows access to the tags that use MIFARE Ultralight. | ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Required permissions**: ohos.permission.NFC_TAG ## tag.getMifareUltralight<sup>9+</sup>
getMifareUltralight(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9)
Obtains a **MifareUltralightTag** object, which allows access to the tags that use MIFARE Ultralight.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. |
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| -------------------- | ---------------------------| | -------------------- | ---------------------------|
| [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) | **MifareUltralightTag** object obtained.| | [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) | **MifareUltralightTag** object obtained.|
## tag.getNdefFormatableTag<sup>9+</sup> **Error codes**
getNdefFormatableTag(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9) For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
Obtains an **NdefFormatableTag** object, which allows access to the tags that are NDEF formattable. | ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Required permissions**: ohos.permission.NFC_TAG ## tag.getNdefFormatable<sup>9+</sup>
getNdefFormatable(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9)
Obtains an **NdefFormatableTag** object, which allows access to the tags that are NDEF formattable.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
...@@ -237,89 +309,376 @@ Obtains an **NdefFormatableTag** object, which allows access to the tags that ar ...@@ -237,89 +309,376 @@ Obtains an **NdefFormatableTag** object, which allows access to the tags that ar
| ------------------ | --------------------------| | ------------------ | --------------------------|
| [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag) | **NdefFormatableTag** object obtained.| | [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag) | **NdefFormatableTag** object obtained.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
## tag.getTagInfo<sup>9+</sup> ## tag.getTagInfo<sup>9+</sup>
getTagInfo(want: Want): [TagInfo](#taginfo) getTagInfo(want: [Want](js-apis-app-ability-want.md#Want)): [TagInfo](#taginfo)
Obtains **TagInfo** from **Want**, which is initialized by the NFC service and contains the attributes required by **TagInfo**. Obtains **TagInfo** from **Want**, which is initialized by the NFC service and contains the attributes required by **TagInfo**.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| want | [Want](js-apis-app-ability-want.md#Want) | Yes | Data obtained from the parameters of the **onCreate** entry function when an ability is dispatched. |
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| [TagInfo](#taginfo) | **TagInfo** object obtained.| | [TagInfo](#taginfo) | **TagInfo** object obtained.|
## TagInfo
Defines the **TagInfo** object, which provides information about the tag technologies supported by a card. ## tag.ndef.makeUriRecord<sup>9+</sup>
**Required permissions**: ohos.permission.NFC_TAG makeUriRecord(uri: string): [NdefRecord](#ndefrecord9);
Creates an NDEF record based on the specified URI.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
| **Name**| **Type**| **Description**| **Parameters**
| -------- | -------- | -------- |
| uid<sup>9+</sup> | number[] | Tag unique identifier (UID). Each number of the UID is a hexadecimal number ranging from **0x00** to **0xFF**.|
| technology<sup>9+</sup> | number[] | Supported technologies. Each number is a constant indicating the supported technology.|
| supportedProfiles | number[] | Supported technologies. This parameter is not supported since API version 9 and is replaced by **technology**.|
## NdefRecord<sup>9+</sup> | Name | Type | Mandatory| Description |
Defines an NDEF tag record. For details, see *NFCForum-TS-NDEF_1.0*. | -------- | ----------------------- | ---- | -------------------------------------- |
| uri | string | Yes| Data to write to the NDEF record.|
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.|
**Example**
```js
import tag from '@ohos.nfc.tag';
try {
let uri = "https://gitee.com/openharmony"; // change it to be correct.
let ndefRecord = tag.ndef.makeUriRecord(uri);
if (ndefRecord != undefined) {
console.log("ndefMessage makeUriRecord rtdType: " + ndefRecord.rtdType);
console.log("ndefMessage makeUriRecord payload: " + ndefRecord.payload);
} else {
console.log("ndefMessage makeUriRecord ndefRecord: " + ndefRecord);
}
} catch (busiError) {
console.log("ndefMessage makeUriRecord catched busiError: " + busiError);
}
```
## tag.ndef.makeTextRecord<sup>9+</sup>
makeTextRecord(text: string, locale: string): [NdefRecord](#ndefrecord9);
Creates an NDEF record based on the specified text data and encoding type.
**System capability**: SystemCapability.Communication.NFC.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| text | string | Yes | Text to write to the NDEF record.|
| locale | string | Yes | Encoding mode of the text.|
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.|
**Example**
```js
import tag from '@ohos.nfc.tag';
try {
let text = "Hello World"; // change it to be correct.
let locale = "en"; // change it to be correct.
let ndefRecord = tag.ndef.makeTextRecord(text, locale);
if (ndefRecord != undefined) {
console.log("ndefMessage makeTextRecord rtdType: " + ndefRecord.rtdType);
console.log("ndefMessage makeTextRecord payload: " + ndefRecord.payload);
} else {
console.log("ndefMessage makeTextRecord ndefRecord: " + ndefRecord);
}
} catch (busiError) {
console.log("ndefMessage makeTextRecord catched busiError: " + busiError);
}
```
## tag.ndef.makeMimeRecord<sup>9+</sup>
makeMimeRecord(mimeType: string, mimeData: number[]): [NdefRecord](#ndefrecord9);
Creates an NDEF record based on the specified MIME data and type.
**System capability**: SystemCapability.Communication.NFC.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| mimeType | string | Yes | MIME type that complies with RFC rules, for example, **text/plain** or **image/jpeg**.|
| mimeData | number[] | Yes | MIME data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.|
**Example**
```js
import tag from '@ohos.nfc.tag';
try {
let mimeType = "text/plain"; // change it to be correct.
let mimeData = [0x01, 0x02, 0x03, 0x04]; // change it to be correct.
let ndefRecord = tag.ndef.makeMimeRecord(mimeType, mimeData);
if (ndefRecord != undefined) {
console.log("ndefMessage makeMimeRecord rtdType: " + ndefRecord.rtdType);
console.log("ndefMessage makeMimeRecord payload: " + ndefRecord.payload);
} else {
console.log("ndefMessage makeMimeRecord ndefRecord: " + ndefRecord);
}
} catch (busiError) {
console.log("ndefMessage makeMimeRecord catched busiError: " + busiError);
}
```
## tag.ndef.makeExternalRecord<sup>9+</sup>
makeExternalRecord(domainName: string, type: string, externalData: number[]): [NdefRecord](#ndefrecord9);
Creates an NDEF record based on application-specific data.
**System capability**: SystemCapability.Communication.NFC.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| domainName | string | Yes | Bundle name of the application or domain name of the organization that releases the applications.|
| type | string | Yes | Type of the application data.|
| externalData | number[] | Yes | Application data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.|
**Example**
```js
import tag from '@ohos.nfc.tag';
try {
let domainName = "ohos.nfc.application"; // change it to be correct.
let type = "test"; // change it to be correct.
let externalData = [0x01, 0x02, 0x03, 0x04]; // change it to be correct.
let ndefRecord = tag.ndef.makeExternalRecord(domainName, type, externalData);
if (ndefRecord != undefined) {
console.log("ndefMessage makeExternalRecord rtdType: " + ndefRecord.rtdType);
console.log("ndefMessage makeExternalRecord payload: " + ndefRecord.payload);
} else {
console.log("ndefMessage makeExternalRecord ndefRecord: " + ndefRecord);
}
} catch (busiError) {
console.log("ndefMessage makeExternalRecord catched busiError: " + busiError);
}
```
## tag.ndef.messageToBytes<sup>9+</sup>
messageToBytes(ndefMessage: [NdefMessage](js-apis-nfctech.md#ndefmessage9)): number[];
Converts an NDEF message to bytes.
**System capability**: SystemCapability.Communication.NFC.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| ndefMessage | [NdefMessage](js-apis-nfctech.md#ndefmessage9) | Yes | NDEF message to convert.|
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| number[] | NDEF message in bytes, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
**Example**
```js
import tag from '@ohos.nfc.tag';
let rawData = [0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]; // MUST can be parsed as NDEF Record.
let ndefMessage;
try {
ndefMessage = tag.ndef.createNdefMessage(rawData);
console.log("ndef createNdefMessage, ndefMessage: " + ndefMessage);
} catch (busiError) {
console.log("ndef createNdefMessage busiError: " + busiError);
}
try {
let rawData2 = tag.ndef.messageToBytes(ndefMessage);
console.log("ndefMessage messageToBytes rawData2: " + rawData2);
} catch (busiError) {
console.log("ndefMessage messageToBytes catched busiError: " + busiError);
}
```
## tag.ndef.createNdefMessage<sup>9+</sup>
createNdefMessage(data: number[]): [NdefMessage](js-apis-nfctech.md#ndefmessage9)
Creates an NDEF message from raw byte data. The data must comply with the NDEF record format. Otherwise, the NDE record list contained in the **NdefMessage** object will be empty.
**System capability**: SystemCapability.Communication.NFC.Core
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| data | number[] | Yes| Raw byte data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**. The data must comply with the NDEF record format.|
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.|
**Example**
```js
import tag from '@ohos.nfc.tag';
let rawData = [0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]; // MUST can be parsed as NDEF Record.
let ndefMessage;
try {
ndefMessage = tag.ndef.createNdefMessage(rawData);
console.log("ndef createNdefMessage, ndefMessage: " + ndefMessage);
} catch (busiError) {
console.log("ndef createNdefMessage busiError: " + busiError);
}
```
## tag.ndef.createNdefMessage<sup>9+</sup>
createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](js-apis-nfctech.md#ndefmessage9)
Creates an NDEF message from the NDEF records list.
**System capability**: SystemCapability.Communication.NFC.Core
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | Yes| NDEF record list used to create the NDEF message. For details, see *NFCForum-TS-NDEF_1.0*.|
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.|
**Example**
```js
import tag from '@ohos.nfc.tag';
let uriRecord = tag.ndef.makeUriRecord("https://gitee.com/openharmony");
let textRecord = tag.ndef.makeTextRecord("Hello World", "en");
let ndefRecords = [uriRecord, textRecord];
let ndefMessage;
try {
ndefMessage = tag.ndef.createNdefMessage(ndefRecords);
console.log("ndef createNdefMessage ndefMessage: " + ndefMessage);
} catch (busiError) {
console.log("ndef createNdefMessage busiError: " + busiError);
}
```
## TagInfo
Defines the **TagInfo** object, which provides information about the tag technologies supported by a card.
**System capability**: SystemCapability.Communication.NFC.Core
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
| **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | -------- |
| uid<sup>9+</sup> | number[] | Yes| No| Tag unique identifier (UID), which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
| technology<sup>9+</sup> | number[] | Yes| No| Supported technologies. Each number is a constant indicating the supported technology.|
| supportedProfiles | number[] | Yes| No| Supported profiles. This parameter is not supported since API version 9. Use [tag.TagInfo#technology](#taginfo) instead.|
| extrasData<sup>9+</sup> | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | Yes| No| Extended attribute value of the tag technology.<br>**System API**: This is a system API.|
| tagRfDiscId<sup>9+</sup> | number | Yes| No| ID allocated when the tag is discovered.<br>**System API**: This is a system API.|
| remoteTagService<sup>9+</sup> | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes| No| Remote object of the NFC service process used for interface communication between the client and the service.<br>**System API**: This is a system API.|
## NdefRecord<sup>9+</sup>
Defines an NDEF record. For details, see *NFCForum-TS-NDEF_1.0*.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
| **Name**| **Type**| **Description**|
| -------- | -------- | -------- | | **Name**| **Type**| **Readable**| **Writable**| **Description**|
| tnf | number | Type name field (TNF) of an NDEF record.| | -------- | -------- | -------- | -------- | -------- |
| rtdType| number[] | Record type definition (RTD) of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| | tnf | number | Yes| No| Type name field (TNF) of the NDEF record.|
| id | number[] | ID of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| | rtdType| number[] | Yes| No| Record type definition (RTD) of the NDEF record. It consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
| payload | number[] | Payload of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| | id | number[] | Yes| No| NDEF record ID, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
| payload | number[] | Yes| No| NDEF payload, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
## Technology Type Definition ## Technology Type Definition
Enumerates the tag technology types. Enumerates the tag technology types.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
| **Name**| **Value**| **Description**| | **Name**| **Value**| **Description**|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| NFC_A | 1 | NFC-A (ISO 14443-3A).| | NFC_A | 1 | NFC-A (ISO 14443-3A).|
| NFC_B | 2 | NFC-A (ISO 14443-3B).| | NFC_B | 2 | NFC-B (ISO 14443-3B).|
| ISO_DEP | 3 | ISO-DEP (ISO 14443-4).| | ISO_DEP | 3 | ISO-DEP (ISO 14443-4).|
| NFC_F | 4 | NFC-F (JIS 6319-4).| | NFC_F | 4 | NFC-F (JIS 6319-4).|
| NFC_V | 5 | NFC-V (ISO 15693).| | NFC_V | 5 | NFC-V (ISO 15693).|
| NDEF | 6 | NDEF.| | NDEF | 6 | NDEF.|
| NDEF_FORMATABLE<sup>9+</sup> | 7 | NDEF formattable.|
| MIFARE_CLASSIC | 8 | MIFARE Classic.| | MIFARE_CLASSIC | 8 | MIFARE Classic.|
| MIFARE_ULTRALIGHT | 9 | MIFARE Ultralight.| | MIFARE_ULTRALIGHT | 9 | MIFARE Ultralight.|
| NDEF_FORMATABLE<sup>9+</sup> | 10 | NDEF formattable.|
## TnfType<sup>9+</sup> ## TnfType<sup>9+</sup>
Enumerates the TNF types. For details, see *NFCForum-TS-NDEF_1.0*. Enumerates the TNF types. For details, see *NFCForum-TS-NDEF_1.0*.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
| **Name**| **Value**| **Description**| | **Name**| **Value**| **Description**|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| TNF_EMPTY | 0x0 | Empty.| | TNF_EMPTY | 0x0 | Empty.|
| TNF_WELL_KNOWN | 0x01 | NFC Forum Well Known Type [NFC RTD].| | TNF_WELL_KNOWN | 0x1 | NFC Forum Well Known Type [NFC RTD].|
| TNF_MEDIA | 0x02 | Media-type as defined in RFC 2046 [RFC 2046].| | TNF_MEDIA | 0x2 | Media-type as defined in RFC 2046 [RFC 2046].|
| TNF_ABSOLUTE_URI | 0x03 | Absolute URI as defined in RFC 3986 [RFC 3986].| | TNF_ABSOLUTE_URI | 0x3 | Absolute URI as defined in RFC 3986 [RFC 3986].|
| TNF_EXT_APP | 0x04 | NFC Forum external type [NFC RTD].| | TNF_EXT_APP | 0x4 | NFC Forum external type [NFC RTD].|
| TNF_UNKNOWN | 0x05 | Unknown.| | TNF_UNKNOWN | 0x5 | Unknown.|
| TNF_UNCHANGED | 0x06 | Unchanged (see section 2.3.3).| | TNF_UNCHANGED | 0x6 | Unchanged (see section 2.3.3 in *NFCForum-TS-NDEF_1.0*).|
## NDEF Record RTD ## NDEF Record RTD
Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-NDEF_1.0*. Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-NDEF_1.0*.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
| **Name**| **Value**| **Description**| | **Name**| **Value**| **Description**|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RTD_TEXT<sup>9+</sup> | [0x54] | NDEF record of the text type.| | RTD_TEXT<sup>9+</sup> | [0x54] | NDEF record of the text type.|
...@@ -328,36 +687,33 @@ Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-ND ...@@ -328,36 +687,33 @@ Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-ND
## NfcForumType<sup>9+</sup> ## NfcForumType<sup>9+</sup>
Enumerates the NFC Forum tag types. Enumerates the NFC Forum tag types.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
| **Name**| **Value**| **Description**| | **Name**| **Value**| **Description**|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| NFC_FORUM_TYPE_1 | 1 | NFC Forum tag type 1.| | NFC_FORUM_TYPE_1 | 1 | NFC Forum tag type 1.|
| NFC_FORUM_TYPE_2 | 2 | NFC Forum tag type 2.| | NFC_FORUM_TYPE_2 | 2 | NFC Forum tag type 2.|
| NFC_FORUM_TYPE_3 | 3 | NFC Forum tag type 3.| | NFC_FORUM_TYPE_3 | 3 | NFC Forum tag type 3.|
| NFC_FORUM_TYPE_4 | 4 | NFC Forum tag type 4.| | NFC_FORUM_TYPE_4 | 4 | NFC Forum tag type 4.|
| MIFARE_CLASSIC | 101 | MIFARE Classic type.| | MIFARE_CLASSIC | 101 | MIFARE Classic.|
## MifareClassicType<sup>9+</sup> ## MifareClassicType<sup>9+</sup>
Enumerates the MIFARE Classic tag types. Enumerates the MIFARE Classic tag types.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
| **Name**| **Value**| **Description**| | **Name**| **Value**| **Description**|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| TYPE_UNKNOWN | -1 | Unknown type.| | TYPE_UNKNOWN | 0 | Unknown type.|
| TYPE_CLASSIC | 0 | MIFARE Classic.| | TYPE_CLASSIC | 1 | MIFARE Classic.|
| TYPE_PLUS | 1 | MIFARE Plus.| | TYPE_PLUS | 2 | MIFARE Plus.|
| TYPE_PRO | 2 | MIFARE Pro.| | TYPE_PRO | 3 | MIFARE Pro.|
## MifareClassicSize<sup>9+</sup> ## MifareClassicSize<sup>9+</sup>
Enumerates the storage sizes of MIFARE Classic tags. Enumerates the sizes of MIFARE Classic tags.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
| **Name**| **Value**| **Description**| | **Name**| **Value**| **Description**|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| MC_SIZE_MINI | 320 | Each tag has 5 sectors, and each sector has 4 blocks.| | MC_SIZE_MINI | 320 | Each tag has 5 sectors, and each sector has 4 blocks.|
...@@ -365,15 +721,14 @@ Enumerates the storage sizes of MIFARE Classic tags. ...@@ -365,15 +721,14 @@ Enumerates the storage sizes of MIFARE Classic tags.
| MC_SIZE_2K | 2048 | Each tag has 32 sectors, and each sector has 4 blocks.| | MC_SIZE_2K | 2048 | Each tag has 32 sectors, and each sector has 4 blocks.|
| MC_SIZE_4K | 4096 | Each tag has 40 sectors, and each sector has 4 blocks.| | MC_SIZE_4K | 4096 | Each tag has 40 sectors, and each sector has 4 blocks.|
### MifareUltralightType<sup>9+</sup> ## MifareUltralightType<sup>9+</sup>
Enumerates the MIFARE Ultralight tag types. Enumerates the MIFARE Ultralight tag types.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
| **Name**| **Value**| **Description**| | **Name**| **Value**| **Description**|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| TYPE_UNKOWN | -1 | Unknown type.| | TYPE_UNKNOWN | 0 | Unknown type.|
| TYPE_ULTRALIGHT | 1 | MIFARE Ultralight.| | TYPE_ULTRALIGHT | 1 | MIFARE Ultralight.|
| TYPE_ULTRALIGHT_C | 2 | MIFARE Ultralight C.| | TYPE_ULTRALIGHT_C | 2 | MIFARE Ultralight C.|
<!--no_check--> <!--no_check-->
# NFC Tag Technologies # nfctech
The **nfctech** module provides APIs for reading and writing tags that use different Near-Field Communication (NFC) technologies. The **nfctech** module provides APIs for reading and writing tags that use different Near-Field Communication (NFC) technologies.
> **NOTE** > **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## **Modules to Import** ## Modules to Import
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
...@@ -13,11 +14,11 @@ import tag from '@ohos.nfc.tag'; ...@@ -13,11 +14,11 @@ import tag from '@ohos.nfc.tag';
## NfcATag ## NfcATag
Provides access to NFC-A (ISO 14443-3A) properties and I/O operations. This class inherits from **TagSession**. Provides APIs to access NFC-A (ISO 14443-3A) properties and perform I/O operations on a tag. This class inherits from **[TagSession](js-apis-tagSession.md)**.
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
The following describes the unique interfaces of **NfcATag**. The following describes the unique APIs of **NfcATag**.
### NfcATag.getSak ### NfcATag.getSak
...@@ -40,8 +41,7 @@ Obtains the SAK value of this NFC-A tag. ...@@ -40,8 +41,7 @@ Obtains the SAK value of this NFC-A tag.
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcA' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcA' correctly.
let sak = nfcA.getSak(); let sak = nfcA.getSak();
console.log("nfcA sak: " + sak); console.log("nfcA sak: " + sak);
``` ```
...@@ -67,18 +67,18 @@ Obtains the ATQA value of this NFC-A tag. ...@@ -67,18 +67,18 @@ Obtains the ATQA value of this NFC-A tag.
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcA' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcA' correctly.
let atqa = nfcA.getAtqa(); let atqa = nfcA.getAtqa();
console.log("nfcA atqa: " + atqa); console.log("nfcA atqa: " + atqa);
``` ```
## NfcBTag ## NfcBTag
Provides access to NFC-B (ISO 14443-3B) properties and I/O operations. This class inherits from **TagSession**. Provides APIs to access NFC-B (ISO 14443-3B) properties and perform I/O operations on a tag. This class inherits from **TagSession**.
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
The following describes the unique interfaces of **NfcBTag**. The following describes the unique APIs of **NfcBTag**.
### NfcBTag.getRespAppData ### NfcBTag.getRespAppData
...@@ -94,14 +94,14 @@ Obtains the application data of this NFC-B tag. ...@@ -94,14 +94,14 @@ Obtains the application data of this NFC-B tag.
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| number[] | Application data obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| | number[] | Application data obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcB' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcB' correctly.
let respAppData = nfcB.getRespAppData(); let respAppData = nfcB.getRespAppData();
console.log("nfcB respAppData: " + respAppData); console.log("nfcB respAppData: " + respAppData);
``` ```
...@@ -120,25 +120,25 @@ Obtains the protocol information of this NFC-B tag. ...@@ -120,25 +120,25 @@ Obtains the protocol information of this NFC-B tag.
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| number[] | Protocol information obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| | number[] | Protocol information obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcB' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcB' correctly.
let respProtocol = nfcB.getRespProtocol(); let respProtocol = nfcB.getRespProtocol();
console.log("nfcB respProtocol: " + respProtocol); console.log("nfcB respProtocol: " + respProtocol);
``` ```
## NfcFTag ## NfcFTag
Provides access to NFC-F (JIS 6319-4) properties and I/O operations. This class inherits from **TagSession**. Provides APIs to access NFC-F (JIS 6319-4) properties and perform I/O operations on a tag. This class inherits from **TagSession**.
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
The following describes the unique interfaces of **NfcFTag**. The following describes the unique APIs of **NfcFTag**.
### NfcFTag.getSystemCode ### NfcFTag.getSystemCode
...@@ -154,14 +154,14 @@ Obtains the system code from this NFC-F tag. ...@@ -154,14 +154,14 @@ Obtains the system code from this NFC-F tag.
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| number[] | System code obtained. Each number in the system code is a hexadecimal number ranging from **0x00** to **0xFF**.| | number[] | System code obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcF' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcF' correctly.
let systemCode = nfcF.getSystemCode(); let systemCode = nfcF.getSystemCode();
console.log("nfcF systemCode: " + systemCode); console.log("nfcF systemCode: " + systemCode);
``` ```
...@@ -174,31 +174,31 @@ Obtains the PMm (consisting of the IC code and manufacturer parameters) informat ...@@ -174,31 +174,31 @@ Obtains the PMm (consisting of the IC code and manufacturer parameters) informat
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| number[] | PMm information obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| | number[] | PMm information obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcF' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcF' correctly.
let pmm = nfcF.getPmm(); let pmm = nfcF.getPmm();
console.log("nfcF pmm: " + pmm); console.log("nfcF pmm: " + pmm);
``` ```
## NfcVTag ## NfcVTag
Provides access to NFC-V (ISO 15693) properties and I/O operations. This class inherits from **TagSession**. Provides APIs to access NFC-V (ISO 15693) properties and perform I/O operations on a tag. This class inherits from **TagSession**.
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
The following describes the unique interfaces of **NfcVTag**. The following describes the unique APIs of **NfcVTag**.
### NfcvTag.getResponseFlags ### NfcvTag.getResponseFlags
...@@ -208,20 +208,20 @@ Obtains the response flags from this NFC-V tag. ...@@ -208,20 +208,20 @@ Obtains the response flags from this NFC-V tag.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| number | Response flags obtained. The value is a hexadecimal number ranging from **0x00** to **0xFF**.| | number | Response flags obtained, which consist of hexadecimal numbers ranging from **0x00** to **0xFF**.|
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcV' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcV' correctly.
let responseFlags = nfcV.getResponseFlags(); let responseFlags = nfcV.getResponseFlags();
console.log("nfcV responseFlags: " + responseFlags); console.log("nfcV responseFlags: " + responseFlags);
``` ```
...@@ -234,54 +234,52 @@ Obtains the data storage format identifier (DSFID) from this NFC-V tag. ...@@ -234,54 +234,52 @@ Obtains the data storage format identifier (DSFID) from this NFC-V tag.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| number | DSFID obtained. The value is a hexadecimal number ranging from **0x00** to **0xFF**.| | number | DSFID obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcV' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcV' correctly.
let dsfId = nfcV.getDsfId(); let dsfId = nfcV.getDsfId();
console.log("nfcV dsfId: " + dsfId); console.log("nfcV dsfId: " + dsfId);
``` ```
## IsoDepTag<sup>9+</sup> ## IsoDepTag<sup>9+</sup>
Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations. This class inherits from **TagSession**. Provides APIs to access ISO-DEP (ISO 14443-4) properties and I/O operations on a tag. This class inherits from **TagSession**.
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
The following describes the unique interfaces of **IsoDepTag**. The following describes the unique APIs of **IsoDepTag**.
### IsoDepTag.getHistoricalBytes<sup>9+</sup> ### IsoDepTag.getHistoricalBytes<sup>9+</sup>
getHistoricalBytes(): number[] getHistoricalBytes(): number[]
Obtains the historical bytes of this tag. Obtains the historical bytes for the given tag. This API applies only to the IsoDep cards that use the NFC-A technology.
**Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| number[] | Historical bytes obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| | number[] | Historical bytes obtained, which consist of hexadecimal numbers ranging from **0x00** to **0xFF**. If the IsoDep tag uses the NFC-B technology, **null** will be returned.|
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly.
let historicalBytes = isoDep.getHistoricalBytes(); let historicalBytes = isoDep.getHistoricalBytes();
console.log("isoDep historicalBytes: " + historicalBytes); console.log("isoDep historicalBytes: " + historicalBytes);
``` ```
...@@ -290,24 +288,22 @@ console.log("isoDep historicalBytes: " + historicalBytes); ...@@ -290,24 +288,22 @@ console.log("isoDep historicalBytes: " + historicalBytes);
getHiLayerResponse(): number[] getHiLayerResponse(): number[]
Obtains the HiLayer response of this tag. Obtains the higher-layer response bytes for the given tag. This API applies only to the IsoDep cards that use the NFC-B technology.
**Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| number[] | HiLayer response obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| | number[] | Higher-layer response bytes obtained, which consist of hexadecimal numbers ranging from **0x00** to **0xFF**. If the IsoDep tag uses the NFC-A technology, **null** will be returned.|
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly.
let hiLayerResponse = isoDep.getHiLayerResponse(); let hiLayerResponse = isoDep.getHiLayerResponse();
console.log("isoDep hiLayerResponse: " + hiLayerResponse); console.log("isoDep hiLayerResponse: " + hiLayerResponse);
``` ```
...@@ -320,7 +316,7 @@ Checks whether an extended application protocol data unit (APDU) is supported. T ...@@ -320,7 +316,7 @@ Checks whether an extended application protocol data unit (APDU) is supported. T
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
...@@ -328,18 +324,39 @@ Checks whether an extended application protocol data unit (APDU) is supported. T ...@@ -328,18 +324,39 @@ Checks whether an extended application protocol data unit (APDU) is supported. T
| ------------------ | --------------------------| | ------------------ | --------------------------|
| Promise&lt;boolean&gt; | Promise used to return the result. If the extended APDU is supported, **true** is returned; otherwise, **false** is returned.| | Promise&lt;boolean&gt; | Promise used to return the result. If the extended APDU is supported, **true** is returned; otherwise, **false** is returned.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly.
isoDep.isExtendedApduSupported()
.then((data) => { // Connect to the tag if it is not connected.
console.log("isoDep isExtendedApduSupported data: " + data); if (!isoDep.isTagConnected()) {
if (!isoDep.connectTag()) {
console.log("isoDep connectTag failed.");
return;
}
}
try {
isoDep.isExtendedApduSupported().then((response) => {
console.log("isoDep isExtendedApduSupported Promise response: " + response);
}).catch((err)=> { }).catch((err)=> {
console.log("isoDep isExtendedApduSupported err: " + err); console.log("isoDep isExtendedApduSupported Promise err: " + err);
}); });
} catch (busiError) {
console.log("isoDep isExtendedApduSupported Promise busiError: " + busiError);
}
``` ```
### IsoDepTag.isExtendedApduSupported<sup>9+</sup> ### IsoDepTag.isExtendedApduSupported<sup>9+</sup>
...@@ -350,7 +367,7 @@ Checks whether an extended APDU is supported. This API uses an asynchronous call ...@@ -350,7 +367,7 @@ Checks whether an extended APDU is supported. This API uses an asynchronous call
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
...@@ -358,251 +375,159 @@ Checks whether an extended APDU is supported. This API uses an asynchronous call ...@@ -358,251 +375,159 @@ Checks whether an extended APDU is supported. This API uses an asynchronous call
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<boolean> | Yes | Callback invoked to return the result. If the extended APDU is supported, **true** is returned; otherwise, **false** is returned.| | callback | AsyncCallback\<boolean> | Yes | Callback invoked to return the result. If the extended APDU is supported, **true** is returned; otherwise, **false** is returned.|
```js **Error codes**
import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
isoDep.isExtendedApduSupported((err, data)=> {
if (err) {
console.log("isoDep isExtendedApduSupported err: " + err);
} else {
console.log("isoDep isExtendedApduSupported data: " + data);
}
});
```
## NdefTag<sup>9+</sup> | ID| Error Message|
| ------- | -------|
Provides access to the tags in the NFC Data Exchange Format (NDEF). This class inherits from **TagSession**. | 3100201 | Tag running state is abnormal in service. |
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
The following describes the unique interfaces of **NdefTag**.
### NdefTag.createNdefMessage<sup>9+</sup>
createNdefMessage(data: number[]): [NdefMessage](#ndefmessage9)
Creates an NDEF message using raw bytes.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| data | number[] | Yes| Raw bytes used to create the message. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.|
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| [NdefMessage](#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.|
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly.
let rawData = [0x00, 0xa4, 0x04, ......]; // change the raw data bytes tobe correct.
let ndefMessage = ndef.createNdefMessage(rawData); // Connect to the tag if it is not connected.
console.log("ndef ndefMessage: " + ndefMessage); if (!isoDep.isTagConnected()) {
if (!isoDep.connectTag()) {
console.log("isoDep connectTag failed.");
return;
}
}
try {
isoDep.isExtendedApduSupported((err, response)=> {
if (err) {
console.log("isoDep isExtendedApduSupported AsyncCallback err: " + err);
} else {
console.log("isoDep isExtendedApduSupported AsyncCallback response: " + response);
}
});
} catch (busiError) {
console.log("isoDep isExtendedApduSupported AsyncCallback busiError: " + busiError);
}
``` ```
## NdefMessage<sup>9+</sup> ## NdefMessage<sup>9+</sup>
### NdefMessage.getNdefRecords<sup>9+</sup> ### NdefMessage.getNdefRecords<sup>9+</sup>
getNdefRecords(): [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] getNdefRecords(): [tag.NdefRecord](js-apis-nfcTag.md#ndefrecord9)[]
Obtains all NDEF records. Obtains all NDEF records.
**Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] | List of NDEF records obtained. For details, see *NFCForum-TS-NDEF_1.0*.| | [tag.NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | List of NDEF records obtained. For details, see *NFCForum-TS-NDEF_1.0*.|
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. // Obtain ndefMessage from tag.ndef.createNdefMessage or ndefTag.getNdefMessage.
let ndefRecords = ndef.getNdefRecords(); // var ndefMessage = tag.ndef.createNdefMessage(...);
// var ndefMessage = ndefTag.getNdefMessage();
let ndefRecords = ndefMessage.getNdefRecords();
console.log("ndef ndefRecords number: " + ndefRecords.length); console.log("ndef ndefRecords number: " + ndefRecords.length);
``` ```
### NdefTag.createNdefMessage<sup>9+</sup> ## NdefTag<sup>9+</sup>
createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](#ndefmessage9)
Creates an NDEF message using the NDEF records.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | Yes| NDEF records used to create the NDEF message. For details, see *NFCForum-TS-NDEF_1.0*.|
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| [NdefMessage](#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.|
**Example**
```js
import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. Provides APIs to access the tags in the NFC Data Exchange Format (NDEF). This class inherits from **TagSession**.
let ndefRecords = [
// record format: tnf, rtdType, id, payload
// 1st record:
{tnf: 0x01, rtdType: [0x54], id: [0x01, 0x02, ...], payload: [0x00, 0xa4, 0x04, ...]},
// 2nd record: **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
{tnf: 0x02, rtdType: [0x55], id: [0x03, 0x04, ...], payload: [0x00, 0xa4, 0x04, ...]},
// other record if has one ... The following describes the unique APIs of **NdefTag**.
];
let ndefMessage = ndef.createNdefMessage(ndefRecords);
console.log("ndef ndefMessage: " + ndefMessage);
```
### NdefTag.getNdefTagType<sup>9+</sup> ### NdefTag.getNdefTagType<sup>9+</sup>
getNdefTagType(): NfcForumType getNdefTagType(): [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9)
Obtains the type of this NDEF tag.
**Required permissions**: ohos.permission.NFC_TAG Obtains the NDEF tag type.
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | NDEF tag type obtained. It can be NFC FORUM TYPE 1, 2, 3, or 4.| | [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | NDEF tag type obtained. It can be NFC FORUM TYPE 1, 2, 3, or 4.|
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly.
let ndefTagType = ndef.getNdefTagType(); let ndefTagType = ndefTag.getNdefTagType();
console.log("ndef ndefTagType: " + ndefTagType); console.log("ndef ndefTagType: " + ndefTagType);
``` ```
### NdefTag.getNdefMessage<sup>9+</sup> ### NdefTag.getNdefMessage<sup>9+</sup>
getNdefMessage(): NdefMessage getNdefMessage(): [NdefMessage](#ndefmessage9)
Obtains the NDEF message.
**Required permissions**: ohos.permission.NFC_TAG Obtains the NDEF message from this NDEF tag.
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| [NdefMessage](#ndefmessage9) | NDEF message obtained. For details, see *NFCForum-TS-NDEF_1.0*.| | [NdefMessage](#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.|
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly.
let ndefMessage = ndef.getNdefMessage(); let ndefMessage = ndefTag.getNdefMessage();
console.log("ndef ndefMessage: " + ndefMessage); console.log("ndef ndefMessage: " + ndefMessage);
``` ```
### NdefTag.isNdefWritable<sup>9+</sup> ### NdefTag.isNdefWritable<sup>9+</sup>
isNdefWritable(): Promise&lt;boolean&gt; isNdefWritable(): boolean;
Checks whether the NDEF tag is writable. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG Check whether this NDEF tag is writable. Before calling the data write API, check whether the write operation is supported.
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| Promise&lt;boolean&gt; | Promise used to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.| | boolean | Promise used to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.|
**Example**
```js
import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly.
ndef.isNdefWritable()
.then((data) => {
console.log("ndef isNdefWritable data: " + data);
}).catch((err)=> {
console.log("ndef isNdefWritable err: " + err);
});
```
### NdefTag.isNdefWritable<sup>9+</sup>
isNdefWritable(callback: AsyncCallback&lt;boolean&gt;): void;
Checks whether the NDEF tag is writable. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<boolean> | Yes | Callback invoked to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.|
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly.
ndef.isNdefWritable((err, data)=> { var isWritable = ndefTag.isNdefWritable();
if (err) { console.log("ndef isNdefWritable: " + isWritable);
console.log("ndef isNdefWritable err: " + err);
} else {
console.log("ndef isNdefWritable data: " + data);
}
});
``` ```
### NdefTag.readNdef<sup>9+</sup> ### NdefTag.readNdef<sup>9+</sup>
readNdef(): Promise\<NdefMessage> readNdef(): Promise\<[NdefMessage](#ndefmessage9)>
Reads the NDEF message from this tag. This API uses a promise to return the result. Reads the NDEF message from this tag. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
...@@ -610,18 +535,38 @@ Reads the NDEF message from this tag. This API uses a promise to return the resu ...@@ -610,18 +535,38 @@ Reads the NDEF message from this tag. This API uses a promise to return the resu
| ------------------ | --------------------------| | ------------------ | --------------------------|
| Promise\<[NdefMessage](#ndefmessage9)> | Promise used to return the message read.| | Promise\<[NdefMessage](#ndefmessage9)> | Promise used to return the message read.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly.
ndef.readNdef()
.then((data) => { // Connect to the tag if it is not connected.
console.log("ndef readNdef data: " + data); if (!ndefTag.isTagConnected()) {
if (!ndefTag.connectTag()) {
console.log("ndefTag connectTag failed.");
return;
}
}
try {
ndefTag.readNdef().then((ndefmessage) => {
console.log("ndef readNdef Promise ndefmessage: " + ndefmessage);
}).catch((err)=> { }).catch((err)=> {
console.log("ndef readNdef err: " + err); console.log("ndef readNdef Promise err: " + err);
}); });
} catch (busiError) {
console.log("ndef readNdef Promise catched busiError: " + busiError);
}
``` ```
### NdefTag.readNdef<sup>9+</sup> ### NdefTag.readNdef<sup>9+</sup>
...@@ -632,38 +577,59 @@ Reads the NDEF message from this tag. This API uses an asynchronous callback to ...@@ -632,38 +577,59 @@ Reads the NDEF message from this tag. This API uses an asynchronous callback to
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<[NdefMessage](#ndefmessage9)> | Yes | Callback invoked to return the result.| | callback | AsyncCallback\<[NdefMessage](#ndefmessage9)> | Yes | Callback invoked to return the NDEF message read.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly.
ndef.readNdef((err, data)=> {
// Connect to the tag if it is not connected.
if (!ndefTag.isTagConnected()) {
if (!ndefTag.connectTag()) {
console.log("ndefTag connectTag failed.");
return;
}
}
try {
ndefTag.readNdef((err, ndefmessage)=> {
if (err) { if (err) {
console.log("ndef readNdef err: " + err); console.log("ndef readNdef AsyncCallback err: " + err);
} else { } else {
console.log("ndef readNdef data: " + data); console.log("ndef readNdef AsyncCallback ndefmessage: " + ndefmessage);
} }
}); });
} catch (busiError) {
console.log("ndef readNdef AsyncCallback catched busiError: " + busiError);
}
``` ```
### NdefTag.writeNdef<sup>9+</sup> ### NdefTag.writeNdef<sup>9+</sup>
writeNdef(msg: NdefMessage): Promise\<number>; writeNdef(msg: NdefMessage): Promise\<void>;
Writes an NDEF message to this tag. This API uses a promise to return the result. Writes an NDEF message to this tag. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
...@@ -671,59 +637,97 @@ Writes an NDEF message to this tag. This API uses a promise to return the result ...@@ -671,59 +637,97 @@ Writes an NDEF message to this tag. This API uses a promise to return the result
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| msg | NdefMessage | Yes | NDEF message to write.| | msg | NdefMessage | Yes | NDEF message to write.|
**Return value** **Error codes**
| **Type**| **Description** | For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ------------------ | --------------------------|
| Promise\<number> | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| | ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly.
let ndefMessage = ndef.createNdefMessage([0x01, 0x02, ...]); // change the raw data to be correct. // NDEF message created from raw data, such as:
let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record.
// or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[])
// Connect to the tag if it is not connected.
if (!ndefTag.isTagConnected()) {
if (!ndefTag.connectTag()) {
console.log("ndefTag connectTag failed.");
return;
}
}
ndef.writeNdef(ndefMessage) try {
.then((data) => { ndefTag.writeNdef(ndefMessage).then(() => {
console.log("ndef writeNdef data: " + data); console.log("ndef writeNdef Promise success.");
}).catch((err)=> { }).catch((err)=> {
console.log("ndef writeNdef err: " + err); console.log("ndef writeNdef err: " + err);
}); });
} catch (busiError) {
console.log("ndef writeNdef Promise catch busiError: " + busiError);
}
``` ```
### NdefTag.writeNdef<sup>9+</sup> ### NdefTag.writeNdef<sup>9+</sup>
writeNdef(msg: NdefMessage, callback: AsyncCallback\<number>): void writeNdef(msg: [NdefMessage](#ndefmessage9), callback: AsyncCallback\<void>): void
Writes an NDEF message to this tag. This API uses an asynchronous callback to return the result. Writes an NDEF message to this tag. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| msg | NdefMessage | Yes | NDEF message to write.| | msg | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write.|
| callback | AsyncCallback\<number> | Yes | Callback invoked to return the result.| | callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly.
let ndefMessage = ndef.createNdefMessage([0x01, 0x02, ...]); // change the raw data to be correct. // NDEF message created from raw data, such as:
ndef.writeNdef(ndefMessage, (err, data)=> { let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record.
// or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[])
// Connect to the tag if it is not connected.
if (!ndefTag.isTagConnected()) {
if (!ndefTag.connectTag()) {
console.log("ndefTag connectTag failed.");
return;
}
}
try {
ndefTag.writeNdef(ndefMessage, (err)=> {
if (err) { if (err) {
console.log("ndef writeNdef err: " + err); console.log("ndef writeNdef AsyncCallback err: " + err);
} else { } else {
console.log("ndef writeNdef data: " + data); console.log("ndef writeNdef AsyncCallback success.");
} }
}); });
} catch (busiError) {
console.log("ndef writeNdef AsyncCallback catch busiError: " + busiError);
}
``` ```
### NdefTag.canSetReadOnly<sup>9+</sup> ### NdefTag.canSetReadOnly<sup>9+</sup>
...@@ -734,7 +738,7 @@ Checks whether this NDEF tag can be set to read-only. ...@@ -734,7 +738,7 @@ Checks whether this NDEF tag can be set to read-only.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
...@@ -742,92 +746,133 @@ Checks whether this NDEF tag can be set to read-only. ...@@ -742,92 +746,133 @@ Checks whether this NDEF tag can be set to read-only.
| ------------------ | --------------------------| | ------------------ | --------------------------|
| boolean| Returns **true** if the tag can be set to read-only; returns **false** otherwise.| | boolean| Returns **true** if the tag can be set to read-only; returns **false** otherwise.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly.
var canSetReadOnly = ndef.canSetReadOnly(); var canSetReadOnly = ndefTag.canSetReadOnly();
console.log("ndef canSetReadOnly: " + canSetReadOnly); console.log("ndef canSetReadOnly: " + canSetReadOnly);
``` ```
### NdefTag.setReadOnly<sup>9+</sup> ### NdefTag.setReadOnly<sup>9+</sup>
setReadOnly(): Promise\<number> setReadOnly(): Promise\<void>
Sets this NDEF tag to read-only. This API uses a promise to return the result. Sets this NDEF tag to read-only. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Error codes**
| **Type**| **Description** | For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ------------------ | --------------------------|
| Promise&lt;number&gt; | Promise used to return the result. If the operation is successful, **0** is returned; otherwise, an error code is returned.| | ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly.
ndef.setReadOnly()
.then((data) => { // Connect to the tag if it is not connected.
console.log("ndef setReadOnly data: " + data); if (!ndefTag.isTagConnected()) {
if (!ndefTag.connectTag()) {
console.log("ndefTag connectTag failed.");
return;
}
}
try {
ndefTag.setReadOnly().then(() => {
console.log("ndef setReadOnly Promise success.");
}).catch((err)=> { }).catch((err)=> {
console.log("ndef setReadOnly err: " + err); console.log("ndef setReadOnly Promise err: " + err);
}); });
} catch (busiError) {
console.log("ndef setReadOnly Promise catch busiError: " + busiError);
}
``` ```
### NdefTag.setReadOnly<sup>9+</sup> ### NdefTag.setReadOnly<sup>9+</sup>
setReadOnly(callback: AsyncCallback\<number>): void setReadOnly(callback: AsyncCallback\<void>): void
Sets this NDEF tag to read-only. This API uses an asynchronous callback to return the result. Sets this NDEF tag to read-only. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<number> | Yes | Callback invoked to return the result.| | callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly.
ndef.setReadOnly((err, data)=> {
// Connect to the tag if it is not connected.
if (!ndefTag.isTagConnected()) {
if (!ndefTag.connectTag()) {
console.log("ndefTag connectTag failed.");
return;
}
}
try {
ndefTag.setReadOnly((err)=> {
if (err) { if (err) {
console.log("ndef setReadOnly err: " + err); console.log("ndef setReadOnly AsyncCallback err: " + err);
} else { } else {
console.log("ndef setReadOnly data: " + data); console.log("ndef setReadOnly AsyncCallback success.");
} }
}); });
} catch (busiError) {
console.log("ndef setReadOnly AsyncCallback catch busiError: " + busiError);
}
``` ```
### NdefTag.getNdefTagTypeString<sup>9+</sup> ### NdefTag.getNdefTagTypeString<sup>9+</sup>
getNdefTagTypeString(type: [NfcForumType](js-apis-nfcTag.md#nfcforumtype9)): string getNdefTagTypeString(type: [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9)): string
Converts an NFC Forum Type tag to a byte array defined in the NFC Forum. Converts an NFC Forum Type tag to a string defined in the NFC Forum.
**Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| type | [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | Yes | NDEF tag type. It can be NFC FORUM type 1, 2, 3, or 4.| | type | [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | Yes | NDEF tag type. It can be NFC FORUM type 1, 2, 3, or 4.|
**Return value** **Return value**
...@@ -840,110 +885,149 @@ Converts an NFC Forum Type tag to a byte array defined in the NFC Forum. ...@@ -840,110 +885,149 @@ Converts an NFC Forum Type tag to a byte array defined in the NFC Forum.
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly.
let ndefTypeString = ndef.getNdefTagTypeString(tag.NFC_FORUM_TYPE_1);
console.log("ndef ndefTypeString: " + ndefTypeString); try {
let ndefTypeString = ndefTag.getNdefTagTypeString(tag.NFC_FORUM_TYPE_1);
console.log("ndef ndefTypeString: " + ndefTypeString);
} catch (busiError) {
console.log("ndef getNdefTagTypeString catch busiError: " + busiError);
}
``` ```
## MifareClassicTag<sup>9+</sup> ## MifareClassicTag<sup>9+</sup>
Provides access to MIFARE Classic properties and I/O operations. This class inherits from **TagSession**. Provides APIs to access MIFARE Classic properties and perform I/O operations on a tag. This class inherits from [TagSession](js-apis-tagSession.md).
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
The following describes the unique interfaces of **MifareClassicTag**. The following describes the unique APIs of **MifareClassicTag**.
### MifareClassicTag.authenticateSector<sup>9+</sup> ### MifareClassicTag.authenticateSector<sup>9+</sup>
authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean): Promise\<boolean> authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean): Promise\<void>
Authenticates a sector using the key. The sector can be accessed only after the authentication is successful. This API uses a promise to return the result. Authenticates a sector using a key. The sector can be accessed only after the authentication is successful. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| sectorIndex | number | Yes | Index of the sector to authenticate.| | sectorIndex | number | Yes | Index of the sector to authenticate. The sector indexes start from **0**.|
| key | number[]| Yes | Key (6 bytes) used for authentication.| | key | number[]| Yes | Key (6 bytes) used for sector authentication.|
| isKeyA | boolean | Yes | Whether the key is key A. The value **true** indicates key A, and **false** indicates key B.| | isKeyA | boolean | Yes | Whether the key is key A. The value **true** indicates key A, and **false** indicates key B.|
**Return value** **Error codes**
| **Type**| **Description** | For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ------------------ | --------------------------|
| Promise\<boolean> | Promise used to return the result. If the authentication is successful, **true** is returned. Otherwise, **false** is returned.| | ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let sectorIndex = 1; // change it to be correct index.
let key = [0x04, 0x05, ....]; // change it to be correct key. // Connect to the tag if it is not connected.
mifareClassic.authenticateSector(sectorIndex, key, true); if (!mifareClassic.isTagConnected()) {
.then((data) => { if (!mifareClassic.connectTag()) {
console.log("mifareClassic authenticateSector data: " + data); console.log("mifareClassic connectTag failed.");
return;
}
}
try {
let sectorIndex = 1; // Change it as required.
let key = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06] // The key must be of 6 bytes.
mifareClassic.authenticateSector(sectorIndex, key, true).then(() => {
console.log("mifareClassic authenticateSector Promise success.");
}).catch((err)=> { }).catch((err)=> {
console.log("mifareClassic authenticateSector err: " + err); console.log("mifareClassic authenticateSector Promise err: " + err);
}); });
} catch (busiError) {
console.log("mifareClassic authenticateSector Promise catch busiError: " + busiError);
}
``` ```
### MifareClassicTag.authenticateSector<sup>9+</sup> ### MifareClassicTag.authenticateSector<sup>9+</sup>
authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback\<boolean>): void authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback\<void>): void
Authenticates a sector using the key. The sector can be accessed only after the authentication is successful. This API uses an asynchronous callback to return the result. Authenticates a sector using a key. The sector can be accessed only after the authentication is successful. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| sectorIndex | number | Yes | Index of the sector to authenticate.| | sectorIndex | number | Yes | Index of the sector to authenticate. The sector indexes start from **0**.|
| key | number[]| Yes | Key (6 bytes) used for authentication.| | key | number[]| Yes | Key (6 bytes) used for sector authentication.|
| isKeyA | boolean | Yes | Whether the key is key A. The value **true** indicates key A, and **false** indicates key B.| | isKeyA | boolean | Yes | Whether the key is key A. The value **true** indicates key A, and **false** indicates key B.|
| callback | AsyncCallback\<boolean> | Yes | Callback invoked to return the result.| | callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
**Example** **Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let sectorIndex = 1; // change it to be correct index.
let key = [0x04, 0x05, ....]; // change it to be correct key. // Connect to the tag if it is not connected.
mifareClassic.authenticateSector(sectorIndex, key, true, (err, data)=> { if (!mifareClassic.isTagConnected()) {
if (!mifareClassic.connectTag()) {
console.log("mifareClassic connectTag failed.");
return;
}
}
try {
let sectorIndex = 1; // Change it as required.
let key = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06] // The key must be of 6 bytes.
mifareClassic.authenticateSector(sectorIndex, key, true, (err)=> {
if (err) { if (err) {
console.log("mifareClassic authenticateSector err: " + err); console.log("mifareClassic authenticateSector AsyncCallback err: " + err);
} else { } else {
console.log("mifareClassic authenticateSector data: " + data); console.log("mifareClassic authenticateSector AsyncCallback success.");
} }
}); });
} catch (busiError) {
console.log("mifareClassic authenticateSector AsyncCallback catch busiError: " + busiError);
}
``` ```
### MifareClassicTag.readSingleBlock<sup>9+</sup> ### MifareClassicTag.readSingleBlock<sup>9+</sup>
readSingleBlock(blockIndex: number): Promise\<number[]> readSingleBlock(blockIndex: number): Promise\<number[]>
Reads a block (16 bytes) on the tag. This API uses a promise to return the result. Reads a block (16 bytes) on this tag. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| blockIndex | number | Yes | Index of the block to read.| | blockIndex | number | Yes | Index of the block to read. The block indexes start from **0**.|
**Return value** **Return value**
...@@ -951,421 +1035,632 @@ Reads a block (16 bytes) on the tag. This API uses a promise to return the resul ...@@ -951,421 +1035,632 @@ Reads a block (16 bytes) on the tag. This API uses a promise to return the resul
| ------------------ | --------------------------| | ------------------ | --------------------------|
| Promise\<number[]> | Promise used to return the block data read.| | Promise\<number[]> | Promise used to return the block data read.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let blockIndex = 1; // change it to be correct index.
mifareClassic.readSingleBlock(blockIndex, (err, data)=> { // Connect to the tag if it is not connected.
if (err) { if (!mifareClassic.isTagConnected()) {
console.log("mifareClassic readSingleBlock err: " + err); if (!mifareClassic.connectTag()) {
} else { console.log("mifareClassic connectTag failed.");
console.log("mifareClassic readSingleBlock data: " + data); return;
} }
}); }
try {
let blockIndex = 1; // Change it as required.
mifareClassic.readSingleBlock(blockIndex).then((data) => {
console.log("mifareClassic readSingleBlock Promise data: " + data);
}).catch((err)=> {
console.log("mifareClassic readSingleBlock Promise err: " + err);
});
} catch (busiError) {
console.log("mifareClassic readSingleBlock Promise catch busiError: " + busiError);
}
``` ```
### MifareClassicTag.readSingleBlock<sup>9+</sup> ### MifareClassicTag.readSingleBlock<sup>9+</sup>
readSingleBlock(blockIndex: number, callback: AsyncCallback\<number[]>): void readSingleBlock(blockIndex: number, callback: AsyncCallback\<number[]>): void
Reads a block (16 bytes) on the tag. This API uses an asynchronous callback to return the result. Reads a block (16 bytes) on this tag. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| blockIndex | number | Yes | Index of the block to read.| | blockIndex | number | Yes | Index of the block to read. The block indexes start from **0**.|
| callback | AsyncCallback\<number[]> | Yes | Callback invoked to return the block read.| | callback | AsyncCallback\<number[]> | Yes | Callback invoked to return the block read.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let blockIndex = 1; // change it to be correct index.
mifareClassic.readSingleBlock(blockIndex, (err, data)=> { // Connect to the tag if it is not connected.
if (!mifareClassic.isTagConnected()) {
if (!mifareClassic.connectTag()) {
console.log("mifareClassic connectTag failed.");
return;
}
}
try {
let blockIndex = 1; // Change it as required.
mifareClassic.readSingleBlock(blockIndex, (err, data)=> {
if (err) { if (err) {
console.log("mifareClassic readSingleBlock err: " + err); console.log("mifareClassic readSingleBlock AsyncCallback err: " + err);
} else { } else {
console.log("mifareClassic readSingleBlock data: " + data); console.log("mifareClassic readSingleBlock AsyncCallback data: " + data);
} }
}); });
} catch (busiError) {
console.log("mifareClassic readSingleBlock AsyncCallback catch busiError: " + busiError);
}
``` ```
### MifareClassicTag.writeSingleBlock<sup>9+</sup> ### MifareClassicTag.writeSingleBlock<sup>9+</sup>
writeSingleBlock(blockIndex: number, data: number[]): Promise\<number> writeSingleBlock(blockIndex: number, data: number[]): Promise\<void>
Writes data to a block on the tag. This API uses a promise to return the result. Writes data to a block on this tag. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| blockIndex | number | Yes | Index of the target block.| | blockIndex | number | Yes | Index of the target block. The block indexes start from **0**.|
| data | number[] | Yes | Data to write.| | data | number[] | Yes | 16-byte data to write.|
**Return value** **Error codes**
| **Type**| **Description** | For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ------------------ | --------------------------|
| Promise\<number> | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| | ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let blockIndex = 1; // change it to be correct index.
let rawData = [0x0a, 0x14, ...]; // change it to be correct data. // Connect to the tag if it is not connected.
mifareClassic.writeSingleBlock(blockIndex, rawData, (err, data)=> { if (!mifareClassic.isTagConnected()) {
if (err) { if (!mifareClassic.connectTag()) {
console.log("mifareClassic writeSingleBlock err: " + err); console.log("mifareClassic connectTag failed.");
} else { return;
console.log("mifareClassic writeSingleBlock data: " + data);
} }
}); }
try {
let blockIndex = 1; // Change it as required.
let rawData = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10]; // MUST be 16 bytes, change it to be correct data.
mifareClassic.writeSingleBlock(blockIndex, rawData).then(() => {
console.log("mifareClassic writeSingleBlock Promise success.");
}).catch((err)=> {
console.log("mifareClassic writeSingleBlock Promise err: " + err);
});
} catch (busiError) {
console.log("mifareClassic writeSingleBlock Promise catch busiError: " + busiError);
}
``` ```
### MifareClassicTag.writeSingleBlock<sup>9+</sup> ### MifareClassicTag.writeSingleBlock<sup>9+</sup>
writeSingleBlock(blockIndex: number, data: number[], callback: AsyncCallback\<number>): void writeSingleBlock(blockIndex: number, data: number[], callback: AsyncCallback\<void>): void
Writes data to a block on the tag. This API uses an asynchronous callback to return the result. Writes data to a block on this tag. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| blockIndex | number | Yes | Index of the target block.| | blockIndex | number | Yes | Index of the target block. The block indexes start from **0**.|
| data | number[] | Yes | Data to write.| | data | number[] | Yes | 16-byte data to write.|
| callback | AsyncCallback\<number> | Yes | Callback invoked to return the result.| | callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let blockIndex = 1; // change it to be correct index.
let rawData = [0x0a, 0x14, ...]; // change it to be correct data. // Connect to the tag if it is not connected.
mifareClassic.writeSingleBlock(blockIndex, rawData, (err, data)=> { if (!mifareClassic.isTagConnected()) {
if (!mifareClassic.connectTag()) {
console.log("mifareClassic connectTag failed.");
return;
}
}
try {
let blockIndex = 1; // Change it as required.
let rawData = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10]; // MUST be 16 bytes, change it to be correct data.
mifareClassic.writeSingleBlock(blockIndex, rawData, (err)=> {
if (err) { if (err) {
console.log("mifareClassic writeSingleBlock err: " + err); console.log("mifareClassic writeSingleBlock AsyncCallback err: " + err);
} else { } else {
console.log("mifareClassic writeSingleBlock data: " + data); console.log("mifareClassic writeSingleBlock AsyncCallback success.");
} }
}); });
} catch (busiError) {
console.log("mifareClassic writeSingleBlock AsyncCallback catch busiError: " + busiError);
}
``` ```
### MifareClassicTag.incrementBlock<sup>9+</sup> ### MifareClassicTag.incrementBlock<sup>9+</sup>
incrementBlock(blockIndex: number, value: number): Promise\<number> incrementBlock(blockIndex: number, value: number): Promise\<void>
Increments a block with data. This API uses a promise to return the result. Increments a block with data. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| blockIndex | number | Yes | Index of the block to increment.| | blockIndex | number | Yes | Index of the block to increment. The block indexes start from **0**.|
| value | number | Yes | Block data to increment. The value is a non-negative number.| | value | number | Yes | Block data to increment. The value cannot be a negative number.|
**Return value** **Error codes**
| **Type**| **Description** | For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ------------------ | --------------------------|
| Promise\<number> | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| | ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let blockIndex = 1; // change it to be correct index.
let value = 0x20; // change it to be correct data. // Connect to the tag if it is not connected.
mifareClassic.incrementBlock(blockIndex, value, (err, data)=> { if (!mifareClassic.isTagConnected()) {
if (err) { if (!mifareClassic.connectTag()) {
console.log("mifareClassic incrementBlock err: " + err); console.log("mifareClassic connectTag failed.");
} else { return;
console.log("mifareClassic incrementBlock data: " + data);
} }
}); }
try {
let blockIndex = 1; // Change it as required.
let value = 0x20; // Change it as required.
mifareClassic.incrementBlock(blockIndex, value).then(() => {
console.log("mifareClassic incrementBlock Promise success.");
}).catch((err)=> {
console.log("mifareClassic incrementBlock Promise err: " + err);
});
} catch (busiError) {
console.log("mifareClassic incrementBlock Promise catch busiError: " + busiError);
}
``` ```
### MifareClassicTag.incrementBlock<sup>9+</sup> ### MifareClassicTag.incrementBlock<sup>9+</sup>
incrementBlock(blockIndex: number, value: number, callback: AsyncCallback\<number>): void incrementBlock(blockIndex: number, value: number, callback: AsyncCallback\<void>): void
Increments a block with data. This API uses an asynchronous callback to return the result. Increments a block with data. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| blockIndex | number | Yes | Index of the block to increment.| | blockIndex | number | Yes | Index of the block to increment. The block indexes start from **0**.|
| value | number | Yes | Block data to increment. The value is a non-negative number.| | value | number | Yes | Block data to increment. The value cannot be a negative number.|
| callback | AsyncCallback\<number> | Yes | Callback invoked to return the result.| | callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let blockIndex = 1; // change it to be correct index.
let value = 0x20; // change it to be correct data. // Connect to the tag if it is not connected.
mifareClassic.incrementBlock(blockIndex, value, (err, data)=> { if (!mifareClassic.isTagConnected()) {
if (!mifareClassic.connectTag()) {
console.log("mifareClassic connectTag failed.");
return;
}
}
try {
let blockIndex = 1; // Change it as required.
let value = 0x20; // Change it as required.
mifareClassic.incrementBlock(blockIndex, value, (err)=> {
if (err) { if (err) {
console.log("mifareClassic incrementBlock err: " + err); console.log("mifareClassic incrementBlock AsyncCallback err: " + err);
} else { } else {
console.log("mifareClassic incrementBlock data: " + data); console.log("mifareClassic incrementBlock AsyncCallback success.");
} }
}); });
} catch (busiError) {
console.log("mifareClassic incrementBlock AsyncCallback catch busiError: " + busiError);
}
``` ```
### MifareClassicTag.decrementBlock<sup>9+</sup> ### MifareClassicTag.decrementBlock<sup>9+</sup>
decrementBlock(blockIndex: number, value: number): Promise\<number> decrementBlock(blockIndex: number, value: number): Promise\<void>
Decrements a block with data. This API uses a promise to return the result. Decrements a block. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| blockIndex | number | Yes | Index of the block to decrement.| | blockIndex | number | Yes | Index of the block to decrement. The block indexes start from **0**.|
| value | number | Yes | Block data to decrement. The value is a non-negative number.| | value | number | Yes | Block data to decrement. The value cannot be a negative number.|
**Return value** **Error codes**
| **Type**| **Description** | For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ------------------ | --------------------------|
| Promise\<number> | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| | ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let blockIndex = 1; // change it to be correct index.
let value = 0x20; // change it to be correct data. // Connect to the tag if it is not connected.
mifareClassic.decrementBlock(blockIndex, value, (err, data)=> { if (!mifareClassic.isTagConnected()) {
if (err) { if (!mifareClassic.connectTag()) {
console.log("mifareClassic decrementBlock err: " + err); console.log("mifareClassic connectTag failed.");
} else { return;
console.log("mifareClassic decrementBlock data: " + data);
} }
}); }
try {
let blockIndex = 1; // Change it as required.
let value = 0x20; // Change it as required.
mifareClassic.decrementBlock(blockIndex, value).then(() => {
console.log("mifareClassic decrementBlock Promise success.");
}).catch((err)=> {
console.log("mifareClassic decrementBlock Promise err: " + err);
});
} catch (busiError) {
console.log("mifareClassic decrementBlock Promise catch busiError: " + busiError);
}
``` ```
### MifareClassicTag.decrementBlock<sup>9+</sup> ### MifareClassicTag.decrementBlock<sup>9+</sup>
decrementBlock(blockIndex: number, value: number, callback: AsyncCallback\<number>): void decrementBlock(blockIndex: number, value: number, callback: AsyncCallback\<void>): void
Decrements a block with data. This API uses an asynchronous callback to return the result. Decrements a block. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| blockIndex | number | Yes | Index of the block to decrement.| | blockIndex | number | Yes | Index of the block to decrement. The block indexes start from **0**.|
| value | number | Yes | Block data to decrement. The value is a non-negative number.| | value | number | Yes | Block data to decrement. The value cannot be a negative number.|
| callback | AsyncCallback\<number> | Yes | Callback invoked to return the result.| | callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let blockIndex = 1; // change it to be correct index.
let value = 0x20; // change it to be correct data. // Connect to the tag if it is not connected.
mifareClassic.decrementBlock(blockIndex, value, (err, data)=> { if (!mifareClassic.isTagConnected()) {
if (!mifareClassic.connectTag()) {
console.log("mifareClassic connectTag failed.");
return;
}
}
try {
let blockIndex = 1; // Change it as required.
let value = 0x20; // Change it as required.
mifareClassic.decrementBlock(blockIndex, value, (err)=> {
if (err) { if (err) {
console.log("mifareClassic decrementBlock err: " + err); console.log("mifareClassic decrementBlock AsyncCallback err: " + err);
} else { } else {
console.log("mifareClassic decrementBlock data: " + data); console.log("mifareClassic decrementBlock AsyncCallback success.");
} }
}); });
} catch (busiError) {
console.log("mifareClassic decrementBlock AsyncCallback catch busiError: " + busiError);
}
``` ```
### MifareClassicTag.transferToBlock<sup>9+</sup> ### MifareClassicTag.transferToBlock<sup>9+</sup>
transferToBlock(blockIndex: number): Promise\<number> transferToBlock(blockIndex: number): Promise\<void>
Copies data from the register to a block. This API uses a promise to return the result. Transfers data from the temporary register to a block. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| blockIndex | number | Yes | Index of the destination block.| | blockIndex | number | Yes | Index of the destination block. The value starts form **0**.|
**Return value** **Error codes**
| **Type**| **Description** | For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ------------------ | --------------------------|
| Promise\<number> | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| | ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let blockIndex = 1; // change it to be correct index.
mifareClassic.transferToBlock(blockIndex, (err, data)=> { // Connect to the tag if it is not connected.
if (err) { if (!mifareClassic.isTagConnected()) {
console.log("mifareClassic transferToBlock err: " + err); if (!mifareClassic.connectTag()) {
} else { console.log("mifareClassic connectTag failed.");
console.log("mifareClassic transferToBlock data: " + data); return;
} }
}); }
try {
let blockIndex = 1; // Change it as required.
mifareClassic.transferToBlock(blockIndex).then(() => {
console.log("mifareClassic transferToBlock Promise success.");
}).catch((err)=> {
console.log("mifareClassic transferToBlock Promise err: " + err);
});
} catch (busiError) {
console.log("mifareClassic transferToBlock Promise catch busiError: " + busiError);
}
``` ```
### MifareClassicTag.transferToBlock<sup>9+</sup> ### MifareClassicTag.transferToBlock<sup>9+</sup>
transferToBlock(blockIndex: number, callback: AsyncCallback\<number>): void transferToBlock(blockIndex: number, callback: AsyncCallback\<void>): void
Copies data from the register to a block. This API uses an asynchronous callback to return the result. Transfers data from the temporary register to a block. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| blockIndex | number | Yes | Index of the destination block.| | blockIndex | number | Yes | Index of the destination block. The value starts form **0**.|
| callback | AsyncCallback\<number> | Yes | Callback invoked to return the result.| | callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let blockIndex = 1; // change it to be correct index.
mifareClassic.transferToBlock(blockIndex, (err, data)=> { // Connect to the tag if it is not connected.
if (!mifareClassic.isTagConnected()) {
if (!mifareClassic.connectTag()) {
console.log("mifareClassic connectTag failed.");
return;
}
}
try {
let blockIndex = 1; // Change it as required.
mifareClassic.transferToBlock(blockIndex, (err)=> {
if (err) { if (err) {
console.log("mifareClassic transferToBlock err: " + err); console.log("mifareClassic transferToBlock AsyncCallback err: " + err);
} else { } else {
console.log("mifareClassic transferToBlock data: " + data); console.log("mifareClassic transferToBlock AsyncCallback success.");
} }
}); });
} catch (busiError) {
console.log("mifareClassic transferToBlock AsyncCallback catch busiError: " + busiError);
}
``` ```
### MifareClassicTag.restoreFromBlock<sup>9+</sup> ### MifareClassicTag.restoreFromBlock<sup>9+</sup>
restoreFromBlock(blockIndex: number): Promise\<number> restoreFromBlock(blockIndex: number): Promise\<void>
Copies data from a block to the register. This API uses a promise to return the result. Restores data in the temporary register from a block. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| blockIndex | number | Yes | Index of the source block.| | blockIndex | number | Yes | Index of the target block. The value starts form **0**.|
**Return value** **Error codes**
| **Type**| **Description** | For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ------------------ | --------------------------|
| Promise\<number> | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| | ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let blockIndex = 1; // change it to be correct index.
mifareClassic.restoreFromBlock(blockIndex) // Connect to the tag if it is not connected.
.then((data) => { if (!mifareClassic.isTagConnected()) {
console.log("mifareClassic restoreFromBlock data: " + data); if (!mifareClassic.connectTag()) {
console.log("mifareClassic connectTag failed.");
return;
}
}
try {
let blockIndex = 1; // Change it as required.
mifareClassic.restoreFromBlock(blockIndex).then(() => {
console.log("mifareClassic restoreFromBlock Promise success.");
}).catch((err)=> { }).catch((err)=> {
console.log("mifareClassic isExtendrestoreFromBlockedApduSupported err: " + err); console.log("mifareClassic restoreFromBlock Promise err: " + err);
}); });
} catch (busiError) {
console.log("mifareClassic restoreFromBlock Promise catch busiError: " + busiError);
}
``` ```
### MifareClassicTag.restoreFromBlock<sup>9+</sup> ### MifareClassicTag.restoreFromBlock<sup>9+</sup>
restoreFromBlock(blockIndex: number, callback: AsyncCallback\<number>): void restoreFromBlock(blockIndex: number, callback: AsyncCallback\<void>): void
Copies data from a block to the register. This API uses an asynchronous callback to return the result. Restores data in the temporary register from a block. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| blockIndex | number | Yes | Index of the source block.| | blockIndex | number | Yes | Index of the target block. The value starts form **0**.|
| callback | AsyncCallback\<number> | Yes | Callback invoked to return the result.| | callback | AsyncCallback\<void> | Yes | Callback invoked to return the result.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let blockIndex = 1; // change it to be correct index.
mifareClassic.restoreFromBlock(blockIndex, (err, data)=> { // Connect to the tag if it is not connected.
if (!mifareClassic.isTagConnected()) {
if (!mifareClassic.connectTag()) {
console.log("mifareClassic connectTag failed.");
return;
}
}
try {
let blockIndex = 1; // Change it as required.
mifareClassic.restoreFromBlock(blockIndex, (err)=> {
if (err) { if (err) {
console.log("mifareClassic restoreFromBlock err: " + err); console.log("mifareClassic restoreFromBlock AsyncCallback err: " + err);
} else { } else {
console.log("mifareClassic restoreFromBlock data: " + data); console.log("mifareClassic restoreFromBlock AsyncCallback success.");
} }
}); });
} catch (busiError) {
console.log("mifareClassic restoreFromBlock AsyncCallback catch busiError: " + busiError);
}
``` ```
### MifareClassicTag.getSectorCount<sup>9+</sup> ### MifareClassicTag.getSectorCount<sup>9+</sup>
...@@ -1374,9 +1669,7 @@ getSectorCount(): number ...@@ -1374,9 +1669,7 @@ getSectorCount(): number
Obtains the number of sectors in this MIFARE Classic tag. Obtains the number of sectors in this MIFARE Classic tag.
**Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC
**Return value** **Return value**
...@@ -1389,7 +1682,7 @@ Obtains the number of sectors in this MIFARE Classic tag. ...@@ -1389,7 +1682,7 @@ Obtains the number of sectors in this MIFARE Classic tag.
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let sectorCount = mifareClassic.getSectorCount(); let sectorCount = mifareClassic.getSectorCount();
console.log("mifareClassic sectorCount: " + sectorCount); console.log("mifareClassic sectorCount: " + sectorCount);
``` ```
...@@ -1400,15 +1693,13 @@ getBlockCountInSector(sectorIndex: number): number ...@@ -1400,15 +1693,13 @@ getBlockCountInSector(sectorIndex: number): number
Obtains the number of blocks in a sector. Obtains the number of blocks in a sector.
**Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| sectorIndex | number | Yes | Index of the sector.| | sectorIndex | number | Yes | Index of the target sector. The sector indexes start from **0**.|
**Return value** **Return value**
...@@ -1421,33 +1712,37 @@ Obtains the number of blocks in a sector. ...@@ -1421,33 +1712,37 @@ Obtains the number of blocks in a sector.
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let blockCountInSector = mifareClassic.getBlockCountInSector();
console.log("mifareClassic blockCountInSector: " + blockCountInSector); try {
let sectorIndex = 1; // Change it as required.
let blockCnt = mifareClassic.getBlockCountInSector(sectorIndex);
console.log("mifareClassic blockCnt: " + blockCnt);
} catch (busiError) {
console.log("mifareClassic getBlockCountInSector catch busiError: " + busiError);
}
``` ```
### MifareClassicTag.getType<sup>9+</sup> ### MifareClassicTag.getType<sup>9+</sup>
getType(): [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) getType(): [tag.MifareClassicType](js-apis-nfcTag.md#mifareclassictype9)
Obtains the type of this MIFARE Classic tag. Obtains the type of this MIFARE Classic tag.
**Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) | Type of the MIFARE Classic tag obtained.| | [tag.MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) | Type of the MIFARE Classic tag obtained.|
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let getType = mifareClassic.getType(); let getType = mifareClassic.getType();
console.log("mifareClassic getType: " + getType); console.log("mifareClassic getType: " + getType);
``` ```
...@@ -1456,11 +1751,9 @@ console.log("mifareClassic getType: " + getType); ...@@ -1456,11 +1751,9 @@ console.log("mifareClassic getType: " + getType);
getTagSize(): number getTagSize(): number
Obtains the tag size (in bytes). For details, see [MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9). Obtains the size of this tag. For details, see [MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9).
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
...@@ -1473,7 +1766,7 @@ Obtains the tag size (in bytes). For details, see [MifareClassicSize](js-apis-nf ...@@ -1473,7 +1766,7 @@ Obtains the tag size (in bytes). For details, see [MifareClassicSize](js-apis-nf
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let tagSize = mifareClassic.getTagSize(); let tagSize = mifareClassic.getTagSize();
console.log("mifareClassic tagSize: " + tagSize); console.log("mifareClassic tagSize: " + tagSize);
``` ```
...@@ -1482,11 +1775,9 @@ console.log("mifareClassic tagSize: " + tagSize); ...@@ -1482,11 +1775,9 @@ console.log("mifareClassic tagSize: " + tagSize);
isEmulatedTag(): boolean isEmulatedTag(): boolean
Checks whether the tag is an emulated tag. Checks whether it is an emulated tag.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
...@@ -1499,7 +1790,7 @@ Checks whether the tag is an emulated tag. ...@@ -1499,7 +1790,7 @@ Checks whether the tag is an emulated tag.
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let isEmulatedTag = mifareClassic.isEmulatedTag(); let isEmulatedTag = mifareClassic.isEmulatedTag();
console.log("mifareClassic isEmulatedTag: " + isEmulatedTag); console.log("mifareClassic isEmulatedTag: " + isEmulatedTag);
``` ```
...@@ -1508,17 +1799,15 @@ console.log("mifareClassic isEmulatedTag: " + isEmulatedTag); ...@@ -1508,17 +1799,15 @@ console.log("mifareClassic isEmulatedTag: " + isEmulatedTag);
getBlockIndex(sectorIndex: number): number getBlockIndex(sectorIndex: number): number
Obtains the first block of a sector. Obtains the index of the first block in a sector.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| sectorIndex | number | Yes | Index of the sector.| | sectorIndex | number | Yes | Index of the target sector. The sector indexes start from **0**.|
**Return value** **Return value**
...@@ -1531,27 +1820,30 @@ Obtains the first block of a sector. ...@@ -1531,27 +1820,30 @@ Obtains the first block of a sector.
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let sectorIndex = 1; // change it to be correct index.
let blockIndex = mifareClassic.getBlockIndex(sectorIndex); try {
console.log("mifareClassic blockIndex: " + blockIndex); let sectorIndex = 1; // Change it as required.
let blockIndex = mifareClassic.getBlockIndex(sectorIndex);
console.log("mifareClassic blockIndex: " + blockIndex);
} catch (busiError) {
console.log("mifareClassic getBlockIndex catch busiError: " + busiError);
}
``` ```
### MifareClassicTag.getSectorIndex<sup>9+</sup> ### MifareClassicTag.getSectorIndex<sup>9+</sup>
getSectorIndex(blockIndex: number): number getSectorIndex(blockIndex: number): number
Obtains the index of a sector that contains the specified block. Obtains the index of a sector that holds the specified block.
**Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Core
**System capability**: SystemCapability.Communication.NFC
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| blockIndex | number | Yes | Index of the block contained in the sector.| | blockIndex | number | Yes| Index of the block. The block indexes start from **0**.|
**Return value** **Return value**
...@@ -1564,41 +1856,54 @@ Obtains the index of a sector that contains the specified block. ...@@ -1564,41 +1856,54 @@ Obtains the index of a sector that contains the specified block.
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly.
let blockIndex = 1; // change it to be correct index.
let sectorIndex = mifareClassic.getSectorIndex(blockIndex); try {
console.log("mifareClassic sectorIndex: " + sectorIndex); let blockIndex = 1; // Change it as required.
let sectorIndex = mifareClassic.getSectorIndex(blockIndex);
console.log("mifareClassic sectorIndex: " + sectorIndex);
} catch (busiError) {
console.log("mifareClassic getSectorIndex catch busiError: " + busiError);
}
``` ```
## MifareUltralightTag<sup>9+</sup> ## MifareUltralightTag<sup>9+</sup>
Provides access to MIFARE Ultralight properties and I/O operations. This class inherits from **TagSession**. Provides APIs to access MIFARE Ultralight properties and perform I/O operations on a tag. This class inherits from **TagSession**.
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
The following describes the unique interfaces of **MifareUltralightTag**. The following describes the unique APIs of **MifareUltralightTag**.
### MifareUltralightTag.readMultiplePages<sup>9+</sup> ### MifareUltralightTag.readMultiplePages<sup>9+</sup>
readMultiplePages(pageIndex: number): Promise\<number[]> readMultiplePages(pageIndex: number): Promise\<number[]>
Reads multiple pages (4 bytes per page). This API uses a promise to return the result. Reads four pages (4 bytes per page) from this tag. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | ------------------------------ | | -------- | ----------------------- | ---- | ------------------------------ |
| pageIndex | number | Yes | Indexes of the pages to read.| | pageIndex | number | Yes | Index of the first page to read. The page indexes start from **0**.|
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| Promise\<number[]> | Promise used to return the data read.| | Promise\<number[]> | Promise used to return the data read, which is 16 bytes in total.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
...@@ -1606,207 +1911,286 @@ Reads multiple pages (4 bytes per page). This API uses a promise to return the r ...@@ -1606,207 +1911,286 @@ Reads multiple pages (4 bytes per page). This API uses a promise to return the r
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly.
let pageIndex = 1; // change it to be correct index.
mifareUltralight.readMultiplePages(pageIndex) // Connect to the tag if it is not connected.
.then((data) => { if (!mifareUltralight.isTagConnected()) {
console.log("mifareUltralight readMultiplePages data: " + data); if (!mifareUltralight.connectTag()) {
console.log("mifareUltralight connectTag failed.");
return;
}
}
try {
let pageIndex = 1; // Change it as required.
mifareUltralight.readMultiplePages(pageIndex).then((data) => {
console.log("mifareUltralight readMultiplePages Promise data = " + data);
}).catch((err)=> { }).catch((err)=> {
console.log("mifareUltralight readMultiplePages err: " + err); console.log("mifareUltralight readMultiplePages Promise err: " + err);
}); });
} catch (busiError) {
console.log("mifareUltralight readMultiplePages Promise catch busiError: " + busiError);
}
``` ```
### MifareUltralightTag.readMultiplePages<sup>9+</sup> ### MifareUltralightTag.readMultiplePages<sup>9+</sup>
readMultiplePages(pageIndex: number, callback: AsyncCallback\<number[]>): void readMultiplePages(pageIndex: number, callback: AsyncCallback\<number[]>): void
Reads multiple pages (4 bytes per page). This API uses an asynchronous callback to return the result. Reads four pages (4 bytes per page) from this tag. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| pageIndex | number | Yes | Indexes of the pages to read.| | pageIndex | number | Yes | Index of the first page to read. The page indexes start from **0**.|
| callback | AsyncCallback\<number[]> | Yes | Callback invoked to return the result.| | callback | AsyncCallback\<number[]> | Yes | Callback invoked to return the data read, which is 16 bytes in total.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly.
let pageIndex = 1; // change it to be correct index.
mifareUltralight.readMultiplePages(pageIndex, (err, data)=> { // Connect to the tag if it is not connected.
if (!mifareUltralight.isTagConnected()) {
if (!mifareUltralight.connectTag()) {
console.log("mifareUltralight connectTag failed.");
return;
}
}
try {
let pageIndex = 1; // Change it as required.
mifareUltralight.readMultiplePages(pageIndex, (err, data)=> {
if (err) { if (err) {
console.log("mifareUltralight readMultiplePages err: " + err); console.log("mifareUltralight readMultiplePages AsyncCallback err: " + err);
} else { } else {
console.log("mifareUltralight readMultiplePages data: " + data); console.log("mifareUltralight readMultiplePages AsyncCallback data: " + data);
} }
}); });
} catch (busiError) {
console.log("mifareUltralight readMultiplePages AsyncCallback catch busiError: " + busiError);
}
``` ```
### MifareUltralightTag.writeSinglePages<sup>9+</sup> ### MifareUltralightTag.writeSinglePage<sup>9+</sup>
writeSinglePages(pageIndex: number, data: number[]): Promise\<number> writeSinglePage(pageIndex: number, data: number[]): Promise\<void>
Writes a page of data. This API uses a promise to return the result. Writes one page (4 bytes) of data to this tag. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| pageIndex | number | Yes | Index of the page.| | pageIndex | number | Yes | Index of the page to write. The page indexes start from **0**.|
| data | number[] | Yes | Data to write.| | data | number[] | Yes | 4-byte data to write.|
**Return value** **Error codes**
| **Type**| **Description** | For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ------------------ | --------------------------|
| Promise\<number> | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| | ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly.
let pageIndex = 1; // change it to be correct index.
let data = [0x01, 0x02, ...]; // change it to be correct raw data. // Connect to the tag if it is not connected.
mifareUltralight.writeSinglePages(pageIndex, data) if (!mifareUltralight.isTagConnected()) {
.then((data) => { if (!mifareUltralight.connectTag()) {
console.log("mifareUltralight writeSinglePages data: " + data); console.log("mifareUltralight connectTag failed.");
return;
}
}
try {
let pageIndex = 1; // Change it as required.
let rawData = [0x01, 0x02, 0x03, 0x04]; // MUST be 4 bytes, change it to be correct raw data.
mifareUltralight.writeSinglePage(pageIndex, rawData).then(() => {
console.log("mifareUltralight writeSinglePage Promise success.");
}).catch((err)=> { }).catch((err)=> {
console.log("mifareUltralight writeSinglePages err: " + err); console.log("mifareUltralight writeSinglePage Promise err: " + err);
}); });
} catch (busiError) {
console.log("mifareUltralight writeSinglePage Promise catch busiError: " + busiError);
}
``` ```
### MifareUltralightTag.writeSinglePages<sup>9+</sup> ### MifareUltralightTag.writeSinglePage<sup>9+</sup>
writeSinglePages(pageIndex: number, data: number[], callback: AsyncCallback\<number>): void writeSinglePage(pageIndex: number, data: number[], callback: AsyncCallback\<void>): void
Writes a page of data. This API uses an asynchronous callback to return the result. Writes one page (4 bytes) of data to this tag. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | ------------------------ | | -------- | ----------------------- | ---- | ------------------------ |
| pageIndex | number | Yes | Index of the page.| | pageIndex | number | Yes | Index of the page to write. The page indexes start from **0**.|
| data | number[] | Yes | Data to write.| | data | number[] | Yes | 4-byte data to write.|
| callback|AsyncCallback\<number> |Yes| Callback invoked to return the result.| | callback|AsyncCallback\<void> |Yes| Callback invoked to return the result.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly.
let pageIndex = 1; // change it to be correct index.
let data = [0x01, 0x02, ...]; // change it to be correct raw data. // Connect to the tag if it is not connected.
mifareUltralight.writeSinglePages(pageIndex, data, (err, data)=> { if (!mifareUltralight.isTagConnected()) {
if (!mifareUltralight.connectTag()) {
console.log("mifareUltralight connectTag failed.");
return;
}
}
try {
let pageIndex = 1; // Change it as required.
let rawData = [0x01, 0x02, 0x03, 0x04]; // MUST be 4 bytes, change it to be correct raw data.
mifareUltralight.writeSinglePage(pageIndex, rawData, (err)=> {
if (err) { if (err) {
console.log("mifareUltralight writeSinglePages err: " + err); console.log("mifareUltralight writeSinglePage AsyncCallback err: " + err);
} else { } else {
console.log("mifareUltralight writeSinglePages data: " + data); console.log("mifareUltralight writeSinglePage AsyncCallback success.");
} }
}); });
} catch (busiError) {
console.log("mifareUltralight writeSinglePage AsyncCallback catch busiError: " + busiError);
}
``` ```
### MifareUltralightTag.getType<sup>9+</sup> ### MifareUltralightTag.getType<sup>9+</sup>
getType(): MifareUltralightType getType(): [tag.MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9)
Obtains the MIFARE Ultralight tag type, in bytes. For details, see [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9).
**Required permissions**: ohos.permission.NFC_TAG Obtains the type of this MIFARE Ultralight tag.
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| MifareUltralightType | MIFARE Ultralight tag type obtained. For details, see [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9).| | [tag.MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9) | Type of the MIFARE Ultralight tag obtained.|
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly.
let getType = mifareClassic.getType(); let getType = mifareClassic.getType();
console.log("mifareUltralight getType: " + getType); console.log("mifareUltralight getType: " + getType);
``` ```
## NdefFormatableTag<sup>9+</sup> ## NdefFormatableTag<sup>9+</sup>
Provides APIs for operating NDEF formattable tags. This class inherits from **TagSession**. Provides APIs for formatting NDEF formattable tags. This class inherits from **TagSession**.
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
The following describes the unique interfaces of **NdefFormatableTag**. The following describes the unique APIs of **NdefFormatableTag**.
### NdefFormatableTag.format<sup>9+</sup> ### NdefFormatableTag.format<sup>9+</sup>
format(message: [NdefMessage](#ndefmessage9)): Promise\<number> format(message: [NdefMessage](#ndefmessage9)): Promise\<void>
Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API uses a promise to return the result. Formats this tag as an NDEF tag, and writes an NDEF message to it. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).| | message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write. If this parameter is **null**, the tag is formatted only (no data will be written).|
**Return value** **Error codes**
| **Type**| **Description** | For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ------------------ | --------------------------|
| Promise\<number> | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| | ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly.
let data = [0x01, 0x02, ...]; // change it to be correct raw data.
let ndefmessage = ndef.createNdefMessage(data);
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. // Connect to the tag if it is not connected.
ndefFormatable.format(ndefmessage, (err, data)=> { if (!ndefFormatable.isTagConnected()) {
if (err) { if (!ndefFormatable.connectTag()) {
console.log("ndefFormatable format err: " + err); console.log("ndefFormatable connectTag failed.");
} else { return;
console.log("ndefFormatable format data: " + data);
} }
}); }
try {
// NDEF message created from raw data, such as:
let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record.
// or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[])
ndefFormatable.format(ndefMessage).then(() => {
console.log("ndefFormatable format Promise success.");
}).catch((err)=> {
console.log("ndefFormatable format Promise err: " + err);
});
} catch (busiError) {
console.log("ndefFormatable format Promise catch busiError: " + busiError);
}
``` ```
### NdefFormatableTag.format<sup>9+</sup> ### NdefFormatableTag.format<sup>9+</sup>
format(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\<number>): void format(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\<void>): void
Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API uses an asynchronous callback to return the result. Formats this tag as an NDEF tag, and writes an NDEF message to it. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
...@@ -1818,7 +2202,7 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API ...@@ -1818,7 +2202,7 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| callback: AsyncCallback\<number> | Callback invoked to return the result.| | callback: AsyncCallback\<void> | Callback invoked to return the result.|
**Example** **Example**
...@@ -1826,82 +2210,108 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API ...@@ -1826,82 +2210,108 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly.
let data = [0x01, 0x02, ...]; // change it to be correct raw data.
let ndefmessage = ndef.createNdefMessage(data); // Connect to the tag if it is not connected.
if (!ndefFormatable.isTagConnected()) {
if (!ndefFormatable.connectTag()) {
console.log("ndefFormatable connectTag failed.");
return;
}
}
try {
// NDEF message created from raw data, such as:
let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record.
// or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[])
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. ndefFormatable.format(ndefMessage, (err)=> {
ndefFormatable.format(ndefmessage, (err, data)=> {
if (err) { if (err) {
console.log("ndefFormatable format err: " + err); console.log("ndefFormatable format AsyncCallback err: " + err);
} else { } else {
console.log("ndefFormatable format data: " + data); console.log("ndefFormatable format AsyncCallback success.");
} }
}); });
} catch (busiError) {
console.log("ndefFormatable format AsyncCallback catch busiError: " + busiError);
}
``` ```
### NdefFormatableTag.formatReadOnly<sup>9+</sup> ### NdefFormatableTag.formatReadOnly<sup>9+</sup>
formatReadOnly(message: [NdefMessage](#ndefmessage9)): Promise\<number> formatReadOnly(message: [NdefMessage](#ndefmessage9)): Promise\<void>
Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and then sets the tag to read-only. This API uses a promise to return the result. Formats this tag as an NDEF tag, writes an NDEF message to it, and then sets the tag to read-only. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).| | message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write. If this parameter is **null**, the tag is formatted only (no data will be written).|
**Return value** **Error codes**
| **Type**| **Description** | For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ------------------ | --------------------------|
| Promise\<number> | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| | ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly.
let data = [0x01, 0x02, ...]; // change it to be correct raw data.
let ndefmessage = ndef.createNdefMessage(data);
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. // Connect to the tag if it is not connected.
ndefFormatable.formatReadOnly(ndefmessage, (err, data)=> { if (!ndefFormatable.isTagConnected()) {
if (err) { if (!ndefFormatable.connectTag()) {
console.log("ndefFormatable formatReadOnly err: " + err); console.log("ndefFormatable connectTag failed.");
} else { return;
console.log("ndefFormatable formatReadOnly data: " + data);
} }
}); }
try {
// NDEF message created from raw data, such as:
let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record.
// or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[])
ndefFormatable.formatReadOnly(ndefMessage).then(() => {
console.log("ndefFormatable formatReadOnly Promise success.");
}).catch((err)=> {
console.log("ndefFormatable formatReadOnly Promise err: " + err);
});
} catch (busiError) {
console.log("ndefFormatable formatReadOnly Promise catch busiError: " + busiError);
}
``` ```
### NdefFormatableTag.formatReadOnly<sup>9+</sup> ### NdefFormatableTag.formatReadOnly<sup>9+</sup>
formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\<number>): void formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\<void>): void
Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and then sets the tag to read-only. This API uses an asynchronous callback to return the result. Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and then sets the tag to read-only. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC **System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).| | message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write. If this parameter is **null**, the tag is formatted only (no data will be written).|
**Return value** **Return value**
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| callback: AsyncCallback\<number> | Callback invoked to return the result.| | callback: AsyncCallback\<void> | Callback invoked to return the result.|
**Example** **Example**
...@@ -1909,16 +2319,29 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the ...@@ -1909,16 +2319,29 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. // Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly.
let data = [0x01, 0x02, ...]; // change it to be correct raw data.
let ndefmessage = ndef.createNdefMessage(data); // Connect to the tag if it is not connected.
if (!ndefFormatable.isTagConnected()) {
if (!ndefFormatable.connectTag()) {
console.log("ndefFormatable connectTag failed.");
return;
}
}
try {
// NDEF message created from raw data, such as:
let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record.
// or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[])
// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. ndefFormatable.formatReadOnly(ndefMessage, (err)=> {
ndefFormatable.formatReadOnly(ndefmessage, (err, data)=> {
if (err) { if (err) {
console.log("ndefFormatable formatReadOnly err: " + err); console.log("ndefFormatable formatReadOnly AsyncCallback err: " + err);
} else { } else {
console.log("ndefFormatable formatReadOnly data: " + data); console.log("ndefFormatable formatReadOnly AsyncCallback success.");
} }
}); });
} catch (busiError) {
console.log("ndefFormatable formatReadOnly AsyncCallback catch busiError: " + busiError);
}
``` ```
# OS Account Management # @ohos.account.osAccount
The **osAccount** module provides basic capabilities for managing OS accounts, including adding, deleting, querying, setting, subscribing to, and enabling an OS account. The **osAccount** module provides basic capabilities for managing OS accounts, including adding, deleting, querying, setting, subscribing to, and enabling an OS account.
> **NOTE**<br> > **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -2708,7 +2709,6 @@ Obtains the constraint source information of an OS account. This API uses a prom ...@@ -2708,7 +2709,6 @@ Obtains the constraint source information of an OS account. This API uses a prom
console.info('queryOsAccountConstraintSourceType exception:' + JSON.stringify(e)); console.info('queryOsAccountConstraintSourceType exception:' + JSON.stringify(e));
} }
``` ```
### isMultiOsAccountEnable<sup>(deprecated)</sup> ### isMultiOsAccountEnable<sup>(deprecated)</sup>
isMultiOsAccountEnable(callback: AsyncCallback&lt;boolean&gt;): void isMultiOsAccountEnable(callback: AsyncCallback&lt;boolean&gt;): void
...@@ -4280,17 +4280,12 @@ Register a PIN inputer. ...@@ -4280,17 +4280,12 @@ Register a PIN inputer.
| ----------| ----------------------- | --- | -------------------------- | | ----------| ----------------------- | --- | -------------------------- |
| inputer | [IInputer](#iinputer8) | Yes | PIN inputer, which is used to obtain the PIN.| | inputer | [IInputer](#iinputer8) | Yes | PIN inputer, which is used to obtain the PIN.|
**Return value**
| Type | Description |
| :------ | :-------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Error codes** **Error codes**
| ID| Error Message | | ID| Error Message |
| -------- | --------------------------- | | -------- | --------------------------- |
| 12300001 | System service exception. | | 12300001 | System service exception. |
| 12300102 | Invalid inputer. |
| 12300103 | Inputer already registered. | | 12300103 | Inputer already registered. |
**Example** **Example**
...@@ -4299,8 +4294,8 @@ Register a PIN inputer. ...@@ -4299,8 +4294,8 @@ Register a PIN inputer.
let password = new Uint8Array([0, 0, 0, 0, 0]); let password = new Uint8Array([0, 0, 0, 0, 0]);
try { try {
let result = pinAuth.registerInputer({ let result = pinAuth.registerInputer({
onGetData: (pinSubType, callback) => { onGetData: (authSubType, callback) => {
callback.onSetData(pinSubType, password); callback.onSetData(authSubType, password);
} }
}); });
console.log('registerInputer result = ' + result); console.log('registerInputer result = ' + result);
...@@ -4327,6 +4322,91 @@ Unregisters this PIN inputer. ...@@ -4327,6 +4322,91 @@ Unregisters this PIN inputer.
pinAuth.unregisterInputer(); pinAuth.unregisterInputer();
``` ```
### InputerManager <sup>10+</sup>
Provides APIs for managing credential inputers.
### registerInputer<sup>10+</sup>
registerInputer(authType: AuthType, inputer: IInputer): void;
Register a credential inputer.
**System API**: This is a system API.
**System capability**: SystemCapability.Account.OsAccount
**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL or ohos.permission.MANAGE_USER_IDM
**Parameters**
| Name | Type | Mandatory| Description |
| ----------| ----------------------- | --- | -------------------------- |
| authType | [AuthType](#authtype8) | Yes | Authentication credential type.|
| inputer | [IInputer](#iinputer8) | Yes | Credential inputer to register.|
**Error codes**
| ID| Error Message |
| -------- | --------------------------- |
| 12300001 | System service exception. |
| 12300102 | Invalid authType or inputer. |
| 12300103 | The credential inputer has been registered. |
| 12300106 | Unsupported authType. |
**Example**
```js
let inputerMgr = new account_osAccount.InputerManager();
let authType = account_osAccount.AuthType.DOMAIN;
let password = new Uint8Array([0, 0, 0, 0, 0]);
try {
InputerMgr.registerInputer(authType, {
onGetData: (authSubType, callback) => {
callback.onSetData(authSubType, password);
}
});
console.log('registerInputer success.');
} catch (e) {
console.log('registerInputer exception = ' + JSON.stringify(e));
}
```
### unregisterInputer<sup>10+</sup>
unregisterInputer(authType: AuthType): void;
Unregisters this credential inputer.
**System API**: This is a system API.
**System capability**: SystemCapability.Account.OsAccount
**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL or ohos.permission.MANAGE_USER_IDM
**Parameters**
| Name | Type | Mandatory| Description |
| ----------| ----------------------- | --- | -------------------------- |
| authType | [AuthType](#authtype8) | Yes | Authentication credential type.|
**Error codes**
| ID| Error Message |
| -------- | --------------------------- |
| 12300002 | Invalid authType. |
**Example**
```js
let inputerMgr = new account_osAccount.InputerManager();
let authType = account_osAccount.AuthType.DOMAIN;
try {
inputerMgr.unregisterInputer(authType);
console.log('unregisterInputer success.');
} catch(err) {
console.log("unregisterInputer err:" + JSON.stringify(err));
}
```
## UserIdentityManager<sup>8+</sup> ## UserIdentityManager<sup>8+</sup>
Provides APIs for user identity management (IDM). Provides APIs for user identity management (IDM).
...@@ -4456,8 +4536,8 @@ Adds credential information, including the credential type, subtype, and token ( ...@@ -4456,8 +4536,8 @@ Adds credential information, including the credential type, subtype, and token (
let password = new Uint8Array([0, 0, 0, 0, 0, 0]); let password = new Uint8Array([0, 0, 0, 0, 0, 0]);
let pinAuth = new account_osAccount.PINAuth(); let pinAuth = new account_osAccount.PINAuth();
pinAuth.registerInputer({ pinAuth.registerInputer({
onGetData: (pinSubType, callback) => { onGetData: (authSubType, callback) => {
callback.onSetData(pinSubType, password); callback.onSetData(authSubType, password);
} }
}); });
let credentialInfo = { let credentialInfo = {
...@@ -4470,12 +4550,12 @@ Adds credential information, including the credential type, subtype, and token ( ...@@ -4470,12 +4550,12 @@ Adds credential information, including the credential type, subtype, and token (
try { try {
userIDM.addCredential(credentialInfo, { userIDM.addCredential(credentialInfo, {
onResult: (result, extraInfo) => { onResult: (result, extraInfo) => {
console.log('updateCredential result = ' + result); console.log('addCredential result = ' + result);
console.log('updateCredential extraInfo = ' + extraInfo); console.log('addCredential extraInfo = ' + extraInfo);
} }
}); });
} catch (e) { } catch (e) {
console.log('updateCredential exception = ' + JSON.stringify(e)); console.log('addCredential exception = ' + JSON.stringify(e));
} }
}); });
``` ```
...@@ -4520,8 +4600,8 @@ Updates credential information. This API uses a callback to return the result. ...@@ -4520,8 +4600,8 @@ Updates credential information. This API uses a callback to return the result.
token: null token: null
}; };
pinAuth.registerInputer({ pinAuth.registerInputer({
onGetData: (pinSubType, callback) => { onGetData: (authSubType, callback) => {
callback.onSetData(pinSubType, password); callback.onSetData(authSubType, password);
} }
}); });
userIDM.openSession((err, challenge) => { userIDM.openSession((err, challenge) => {
...@@ -4820,7 +4900,7 @@ Provides callbacks for PIN operations. ...@@ -4820,7 +4900,7 @@ Provides callbacks for PIN operations.
### onSetData<sup>8+</sup> ### onSetData<sup>8+</sup>
onSetData: (pinSubType: AuthSubType, data: Uint8Array) => void; onSetData: (authSubType: AuthSubType, data: Uint8Array) => void;
**System API**: This is a system API. **System API**: This is a system API.
...@@ -4832,7 +4912,7 @@ Called to set data in a PIN operation. ...@@ -4832,7 +4912,7 @@ Called to set data in a PIN operation.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | ---------------------------------------- | ---- | ----------------------------------------------- | | ---------- | ---------------------------------------- | ---- | ----------------------------------------------- |
| pinSubType | [AuthSubType](#authsubtype8) | Yes | Credential subtype. | | authSubType | [AuthSubType](#authsubtype8) | Yes | Credential subtype. |
| data | Uint8Array | Yes | Data (credential) to set. The data is used for authentication and operations for adding and modifying credentials.| | data | Uint8Array | Yes | Data (credential) to set. The data is used for authentication and operations for adding and modifying credentials.|
**Example** **Example**
...@@ -4840,11 +4920,11 @@ Called to set data in a PIN operation. ...@@ -4840,11 +4920,11 @@ Called to set data in a PIN operation.
let password = new Uint8Array([0, 0, 0, 0, 0, 0]); let password = new Uint8Array([0, 0, 0, 0, 0, 0]);
let passwordNumber = new Uint8Array([1, 2, 3, 4]); let passwordNumber = new Uint8Array([1, 2, 3, 4]);
let inputer = { let inputer = {
onGetData: (pinSubType, callback) => { onGetData: (authSubType, callback) => {
if (pinSubType == account_osAccount.AuthSubType.PIN_NUMBER) { if (authSubType == account_osAccount.AuthSubType.PIN_NUMBER) {
callback.onSetData(pinSubType, passwordNumber); callback.onSetData(authSubType, passwordNumber);
} else { } else {
callback.onSetData(pinSubType, password); callback.onSetData(authSubType, password);
} }
} }
}; };
...@@ -4852,13 +4932,13 @@ Called to set data in a PIN operation. ...@@ -4852,13 +4932,13 @@ Called to set data in a PIN operation.
## IInputer<sup>8+</sup> ## IInputer<sup>8+</sup>
Provides callbacks for the PIN input box. Provides callbacks for credential inputers.
**System API**: This is a system API. **System API**: This is a system API.
### onGetData<sup>8+</sup> ### onGetData<sup>8+</sup>
onGetData: (pinSubType: AuthSubType, callback: IInputData) => void; onGetData: (authSubType: AuthSubType, callback: IInputData) => void;
Called to obtain data. Called to obtain data.
...@@ -4877,11 +4957,11 @@ Called to obtain data. ...@@ -4877,11 +4957,11 @@ Called to obtain data.
let password = new Uint8Array([0, 0, 0, 0, 0, 0]); let password = new Uint8Array([0, 0, 0, 0, 0, 0]);
let passwordNumber = new Uint8Array([1, 2, 3, 4]); let passwordNumber = new Uint8Array([1, 2, 3, 4]);
let inputer = { let inputer = {
onGetData: (pinSubType, callback) => { onGetData: (authSubType, callback) => {
if (pinSubType == account_osAccount.AuthSubType.PIN_NUMBER) { if (authSubType == account_osAccount.AuthSubType.PIN_NUMBER) {
callback.onSetData(pinSubType, passwordNumber); callback.onSetData(authSubType, passwordNumber);
} else { } else {
callback.onSetData(pinSubType, password); callback.onSetData(authSubType, password);
} }
} }
}; };
...@@ -5157,6 +5237,8 @@ Enumerates the authentication credential types. ...@@ -5157,6 +5237,8 @@ Enumerates the authentication credential types.
| ----- | ----- | ---------------- | | ----- | ----- | ---------------- |
| PIN | 1 | PIN authentication.| | PIN | 1 | PIN authentication.|
| FACE | 2 | Facial authentication.| | FACE | 2 | Facial authentication.|
| FINGERPRINT<sup>10+</sup> | 4 | Fingerprint authentication.|
| DOMAIN<sup>10+</sup> | 1024 | Domain authentication.|
## AuthSubType<sup>8+</sup> ## AuthSubType<sup>8+</sup>
...@@ -5170,9 +5252,10 @@ Enumerates the authentication credential subtypes. ...@@ -5170,9 +5252,10 @@ Enumerates the authentication credential subtypes.
| ---------- | ----- | ------------------ | | ---------- | ----- | ------------------ |
| PIN_SIX | 10000 | Six-digit PIN. | | PIN_SIX | 10000 | Six-digit PIN. |
| PIN_NUMBER | 10001 | Custom PIN.| | PIN_NUMBER | 10001 | Custom PIN.|
| PIN_MIXED | 10002 | Custom mixed credential.| | PIN_MIXED | 10002 | Custom mixed credentials.|
| FACE_2D | 20000 | 2D face credential. | | FACE_2D | 20000 | 2D face credential. |
| FACE_3D | 20001 | 3D face credential. | | FACE_3D | 20001 | 3D face credential. |
| DOMAIN_MIXED<sup>10+</sup> | 10240001 | Mixed domain authentication credentials. |
## AuthTrustLevel<sup>8+</sup> ## AuthTrustLevel<sup>8+</sup>
......
# RPC # @ohos.rpc
The **RPC** module implements communication between processes, including inter-process communication (IPC) on a single device and remote procedure call (RPC) between processes on difference devices. IPC is implemented based on the Binder driver, and RPC is based on the DSoftBus driver. The **RPC** module implements communication between processes, including inter-process communication (IPC) on a single device and remote procedure call (RPC) between processes on difference devices. IPC is implemented based on the Binder driver, and RPC is based on the DSoftBus driver.
> **NOTE**<br> > **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> This module supports return of error codes since API version 9. > This module supports return of error codes since API version 9.
...@@ -24,7 +26,7 @@ The APIs of this module return exceptions since API version 9. The following tab ...@@ -24,7 +26,7 @@ The APIs of this module return exceptions since API version 9. The following tab
| ------------------------------------- | ------- | --------------------------------------------- | | ------------------------------------- | ------- | --------------------------------------------- |
| CHECK_PARAM_ERROR | 401 | Parameter check failed. | | CHECK_PARAM_ERROR | 401 | Parameter check failed. |
| OS_MMAP_ERROR | 1900001 | Failed to call mmap. | | OS_MMAP_ERROR | 1900001 | Failed to call mmap. |
| OS_IOCTL_ERROR | 1900002 | Failed to execute **ioctl** with the shared memory file descriptor.| | OS_IOCTL_ERROR | 1900002 | Failed to call **ioctl** with the shared memory file descriptor.|
| WRITE_TO_ASHMEM_ERROR | 1900003 | Failed to write data to the shared memory. | | WRITE_TO_ASHMEM_ERROR | 1900003 | Failed to write data to the shared memory. |
| READ_FROM_ASHMEM_ERROR | 1900004 | Failed to read data from the shared memory. | | READ_FROM_ASHMEM_ERROR | 1900004 | Failed to read data from the shared memory. |
| ONLY_PROXY_OBJECT_PERMITTED_ERROR | 1900005 | This operation is allowed only on the proxy object. | | ONLY_PROXY_OBJECT_PERMITTED_ERROR | 1900005 | This operation is allowed only on the proxy object. |
...@@ -123,7 +125,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -123,7 +125,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
readRemoteObject(): IRemoteObject readRemoteObject(): IRemoteObject
Reads a remote object from **MessageSequence**. You can use this API to deserialize the **MessageSequence** object to generate an **IRemoteObject**. The remote object is read in the order in which it is written to this **MessageSequence** object. Reads the remote object from **MessageSequence**. You can use this API to deserialize the **MessageSequence** object to generate an **IRemoteObject**. The remote object is read in the order in which it is written to this **MessageSequence** object.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -405,7 +407,7 @@ Obtains the read position of this **MessageSequence** object. ...@@ -405,7 +407,7 @@ Obtains the read position of this **MessageSequence** object.
| Type| Description| | Type| Description|
| ------ | ------ | | ------ | ------ |
| number | Current read position of the **MessageSequence** object.| | number | Read position obtained.|
**Example** **Example**
...@@ -427,7 +429,7 @@ Obtains the write position of this **MessageSequence** object. ...@@ -427,7 +429,7 @@ Obtains the write position of this **MessageSequence** object.
| Type| Description| | Type| Description|
| ------ | ----- | | ------ | ----- |
| number | Current write position of the **MessageSequence** object.| | number | Write position obtained.|
**Example** **Example**
...@@ -504,7 +506,7 @@ Moves the write pointer to the specified position. ...@@ -504,7 +506,7 @@ Moves the write pointer to the specified position.
writeByte(val: number): void writeByte(val: number): void
Writes a Byte value to this **MessageSequence** object. Writes a byte value to this **MessageSequence** object.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -538,7 +540,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -538,7 +540,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
readByte(): number readByte(): number
Reads the Byte value from this **MessageSequence** object. Reads the byte value from this **MessageSequence** object.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -2856,7 +2858,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2856,7 +2858,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
readFileDescriptor(): number readFileDescriptor(): number
Reads a file descriptor from this **MessageSequence** object. Reads the file descriptor from this **MessageSequence** object.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -4017,7 +4019,7 @@ Writes a string to this **MessageParcel** object. ...@@ -4017,7 +4019,7 @@ Writes a string to this **MessageParcel** object.
readString(): string readString(): string
Reads a string from this **MessageParcel** object. Reads the string from this **MessageParcel** object.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
......
# NFC Tag Session # tagSession
The **tagSession** module provides common APIs for establishing connections and transferring data. The **tagSession** module provides common APIs for establishing connections and transferring data.
> **NOTE**<br> > **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## **Modules to Import** ## **Modules to Import**
...@@ -15,17 +16,15 @@ import tag from '@ohos.nfc.tag'; ...@@ -15,17 +16,15 @@ import tag from '@ohos.nfc.tag';
Provides common APIs for establishing connections and transferring data. **tagSession** is the base class of all [NFC tag technologies](js-apis-nfctech.md). Provides common APIs for establishing connections and transferring data. **tagSession** is the base class of all [NFC tag technologies](js-apis-nfctech.md).
A child class instance is required to access the following interfaces. You can use **get**XX**Tag()** to obtain a child class instance. A child class instance is required to access the following interfaces. You can use **get**XXX() to obtain a child class instance.
The specific API varies with the NFC tag technology in use. For details, see [NFC Tags](js-apis-nfcTag.md). The specific API varies with the NFC tag technology in use. For details, see [NFC Tags](js-apis-nfcTag.md).
### tagSession.connectTag ### tagSession.getTagInfo
connectTag(): boolean;
Connects to this tag. getTagInfo(): tag.TagInfo
Call this API to set up a connection before reading data from or writing data to a tag. Obtains the **tagInfo** object provided by the NFC service when the tag is dispatched.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -35,23 +34,25 @@ Call this API to set up a connection before reading data from or writing data to ...@@ -35,23 +34,25 @@ Call this API to set up a connection before reading data from or writing data to
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | TagInfo | **Taginfo** object obtained.|
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// tagInfo is an object given by the NFC service when a tag is dispatched. // tagInfo is an object provided by the NFC service when a tag is dispatched.
let isNfcConnected = tag.getXXXTag(taginfo).connectTag(); // getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags.
console.log("isNfcConnected:" +isNfcConnected);
let tagInfo = tag.getIsoDep(tagInfo).getTagInfo();
console.log("tag tagInfo: " + tagInfo);
``` ```
### tagSession.reset() ### tagSession.connectTag
reset(): void connectTag(): boolean;
Resets the connection to this tag and restores the default timeout duration for writing data to the tag. Connects to this tag. Call this API to set up a connection before reading data from or writing data to a tag.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -68,9 +69,32 @@ Resets the connection to this tag and restores the default timeout duration for ...@@ -68,9 +69,32 @@ Resets the connection to this tag and restores the default timeout duration for
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// tagInfo is an object given by the NFC service when a tag is dispatched. // tagInfo is an object provided by the NFC service when a tag is dispatched.
let reset = tag.getXXXTag(taginfo).reset(); // getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags.
console.log("reset:" +reset);
let connectStatus = tag.getIsoDep(tagInfo).connectTag();
console.log("connectStatus: " + connectStatus);
```
### tagSession.reset()
reset(): void
Resets the connection to this tag.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**Example**
```js
import tag from '@ohos.nfc.tag';
// tagInfo is an object provided by the NFC service when a tag is dispatched.
// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags.
tag.getIsoDep(tagInfo).reset();
``` ```
### tagSession.isTagConnected ### tagSession.isTagConnected
...@@ -94,16 +118,18 @@ Checks whether the tag is connected. ...@@ -94,16 +118,18 @@ Checks whether the tag is connected.
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// tagInfo is an object given by the NFC service when a tag is dispatched. // tagInfo is an object provided by the NFC service when a tag is dispatched.
let isTagConnected = tag.getXXXTag(taginfo).isTagConnected(); // getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags.
console.log("isTagConnected:" +isTagConnected);
let isTagConnected = tag.getIsoDep(tagInfo).isTagConnected();
console.log("isTagConnected: " + isTagConnected);
``` ```
### tagSession.getMaxSendLength ### tagSession.getMaxSendLength
getMaxSendLength(): number getMaxSendLength(): number
Obtains the maximum length of the data that can be sent to the tag. Obtains the maximum length of the data that can be sent to this tag.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -113,14 +139,167 @@ Obtains the maximum length of the data that can be sent to the tag. ...@@ -113,14 +139,167 @@ Obtains the maximum length of the data that can be sent to the tag.
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| number | Maximum data length obtained.| | number | Maximum data length obtained. The value cannot be a negative number.|
**Example**
```js
import tag from '@ohos.nfc.tag';
// tagInfo is an object provided by the NFC service when a tag is dispatched.
// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags.
let maxSendLen = tag.getIsoDep(tagInfo).getMaxSendLength();
console.log("tag maxSendLen: " + maxSendLen);
```
### tagSession.getSendDataTimeout
getSendDataTimeout(): number
Obtains the timeout period for sending data to this tag, in milliseconds.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| number | Timeout period obtained, in milliseconds. The value cannot be a negative number.|
**Example**
```js
import tag from '@ohos.nfc.tag';
// tagInfo is an object provided by the NFC service when a tag is dispatched.
// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags.
let sendDataTimeout = tag.getIsoDep(tagInfo).getSendDataTimeout();
console.log("tag sendDataTimeout: " + sendDataTimeout);
```
### tagSession.setSendDataTimeout
setSendDataTimeout(timeout: number): boolean
Sets the timeout period for sending data to this tag, in milliseconds.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| timeout | number | Yes| Timeout period to set, in milliseconds. The value cannot be a negative number.|
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| boolean | Returns **true** if the timeout period is set successfully; returns **false** otherwise.|
**Example**
```js
import tag from '@ohos.nfc.tag';
// tagInfo is an object provided by the NFC service when a tag is dispatched.
// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags.
let timeoutMs = 700; // Change it as required.
let setStatus = tag.getIsoDep(tagInfo).setSendDataTimeout(timeoutMs);
console.log("tag setSendDataTimeout setStatus: " + setStatus);
```
### tagSession.sendData
sendData(data: number[]): Promise<number[]>
Sends data to this tag. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| data | number[] | Yes| Data to send. The data consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| Promise<number[]> | Promise used to return the response from the tag. The response consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
**Example**
```js
import tag from '@ohos.nfc.tag';
// tagInfo is an object provided by the NFC service when a tag is dispatched.
// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags.
// Connect to the tag if it is not connected.
if (!tag.getIsoDep(tagInfo).isTagConnected()) {
if (!tag.getIsoDep(tagInfo).connectTag()) {
console.log("tagSession connectTag failed.");
return;
}
}
let cmdData = [0x01, 0x02, 0x03, 0x04]; // Change it as required.
tag.getIsoDep(tagInfo).sendData(cmdData).then((response) => {
console.log("tagSession sendData Promise response: " + response);
}).catch((err)=> {
console.log("tagSession sendData Promise err: " + err);
});
```
### tagSession.sendData
sendData(data: number[], callback: AsyncCallback<number[]>): void
Sends data to this tag. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| data | number[] | Yes| Data to send. The data consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
| callback | AsyncCallback<number[]> | Yes| Callback invoked to return the response from the tag. The response consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
**Example** **Example**
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// tagInfo is an object given by the NFC service when a tag is dispatched. // tagInfo is an object provided by the NFC service when a tag is dispatched.
let mazSendLen = tag.getXXXTag(taginfo).getMaxSendLength(); // getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags.
console.log("mazSendLen:" +mazSendLen);
// Connect to the tag if it is not connected.
if (!tag.getIsoDep(tagInfo).isTagConnected()) {
if (!tag.getIsoDep(tagInfo).connectTag()) {
console.log("tagSession connectTag failed.");
return;
}
}
let cmdData = [0x01, 0x02, 0x03, 0x04]; // Change it as required.
tag.getIsoDep(tagInfo).sendData(cmdData, (err, response)=> {
if (err) {
console.log("tagSession sendData AsyncCallback err: " + err);
} else {
console.log("tagSession sendData AsyncCallback response: " + response);
}
});
``` ```
# WLAN # @ohos.wifi (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 other devices over 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 other devices over WLAN.
> **NOTE**<br> > **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. > 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.
...@@ -166,20 +168,17 @@ Represents WLAN hotspot information. ...@@ -166,20 +168,17 @@ Represents WLAN hotspot information.
**System capability**: SystemCapability.Communication.WiFi.STA **System capability**: SystemCapability.Communication.WiFi.STA
| **Name**| **Type**| **Readable/Writable**| **Description**| | **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| ssid | string | Read only| Service set identifier (SSID) of the hotspot, in UTF-8 format.| | ssid | string | Yes| No| Service set identifier (SSID) of the hotspot, in UTF-8 format.|
| bssid | string | Read only| Basic service set identifier (BSSID) of the hotspot.| | bssid | string | Yes| No| Basic service set identifier (BSSID) of the hotspot.|
| capabilities | string | Read only| Hotspot capabilities.| | capabilities | string | Yes| No| Hotspot capabilities.|
| securityType | [WifiSecurityType](#wifisecuritytype) | Read only| WLAN security type.| | securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| WLAN security type.|
| rssi | number | Read only| Received signal strength indicator (RSSI) of the hotspot, in dBm.| | rssi | number | Yes| No| Received signal strength indicator (RSSI) of the hotspot, in dBm.|
| band | number | Read only| Frequency band of the WLAN access point (AP).| | band | number | Yes| No| Frequency band of the WLAN access point (AP).|
| frequency | number | Read only| Frequency of the WLAN AP.| | frequency | number | Yes| No| Frequency of the WLAN AP.|
| channelWidth | number | Read only| Channel width of the WLAN AP.| | channelWidth | number | Yes| No| Channel width of the WLAN AP.|
| centerFrequency0<sup>9+</sup> | number | Read only| Center frequency of the hotspot.| | timestamp | number | Yes| No| Timestamp.|
| centerFrequency1<sup>9+</sup> | number | Read only| Center frequency of the hotspot. If the hotspot uses two non-overlapping WLAN channels, two center frequencies, namely **centerFrequency0** and **centerFrequency1**, are returned.|
| infoElems<sup>9+</sup> | Array&lt;[WifiInfoElem](#wifiinfoelem9)&gt; | Read only| Information elements.|
| timestamp | number | Read only| Timestamp.|
## WifiSecurityType ## WifiSecurityType
...@@ -189,50 +188,13 @@ Enumerates the WLAN security types. ...@@ -189,50 +188,13 @@ Enumerates the WLAN security types.
**System capability**: SystemCapability.Communication.WiFi.Core **System capability**: SystemCapability.Communication.WiFi.Core
| **Name**| **Default Value**| **Description**| | **Name**| **Value**| **Description**|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| WIFI_SEC_TYPE_INVALID | 0 | Invalid security type.| | WIFI_SEC_TYPE_INVALID | 0 | Invalid security type.|
| WIFI_SEC_TYPE_OPEN | 1 | Open security type.| | WIFI_SEC_TYPE_OPEN | 1 | Open security type.|
| WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP).| | WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP).|
| WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK).| | WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK).|
| WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE).| | WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE).|
| WIFI_SEC_TYPE_EAP<sup>9+</sup> | 5 | Extensible Authentication protocol (EAP).|
| WIFI_SEC_TYPE_EAP_SUITE_B<sup>9+</sup> | 6 | Suite B 192-bit encryption.|
| WIFI_SEC_TYPE_OWE<sup>9+</sup> | 7 | Opportunistic Wireless Encryption (OWE).|
| WIFI_SEC_TYPE_WAPI_CERT<sup>9+</sup> | 8 | WLAN Authentication and Privacy Infrastructure (WAPI) in certificate-based mode (WAPI-CERT).|
| WIFI_SEC_TYPE_WAPI_PSK<sup>9+</sup> | 9 | WAPI-PSK.|
## WifiInfoElem<sup>9+</sup>
Represents a WLAN information element.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.STA
| **Name**| **Type**| **Readable/Writable**| **Description**|
| -------- | -------- | -------- | -------- |
| eid | number | Read only| ID of the information element.|
| content | Uint8Array | Read only| Content of the information element.|
## WifiChannelWidth<sup>9+</sup>
Enumerates the WLAN channel widths.
**System capability**: SystemCapability.Communication.WiFi.STA
| **Name**| **Default Value**| **Description**|
| -------- | -------- | -------- |
| WIDTH_20MHZ | 0 | 20 MHz.|
| WIDTH_40MHZ | 1 | 40 MHz.|
| WIDTH_80MHZ | 2 | 80 MHz.|
| WIDTH_160MHZ | 3 | 160 MHz.|
| WIDTH_80MHZ_PLUS | 4 | 80 MHz<sup>+</sup>.|
| WIDTH_INVALID | 5 | Invalid value.|
## wifi.getScanInfosSync<sup>9+</sup> ## wifi.getScanInfosSync<sup>9+</sup>
...@@ -274,7 +236,7 @@ Adds network configuration. This API uses a promise to return the result. ...@@ -274,7 +236,7 @@ Adds network configuration. This API uses a promise to return the result.
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the WLAN configuration ID. If **-1** is returned, the operation has failed.| | Promise&lt;number&gt; | Promise used to return the WLAN configuration ID. If **-1** is returned, the network configuration fails to be added.|
## WifiDeviceConfig ## WifiDeviceConfig
...@@ -283,33 +245,32 @@ Represents the WLAN configuration. ...@@ -283,33 +245,32 @@ Represents the WLAN configuration.
**System capability**: SystemCapability.Communication.WiFi.STA **System capability**: SystemCapability.Communication.WiFi.STA
| **Name**| **Type**| **Readable/Writable**| **Description**| | **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| | ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.|
| bssid | string | Read only| BSSID of the hotspot.| | bssid | string | Yes| No| BSSID of the hotspot.|
| preSharedKey | string | Read only| PSK of the hotspot.| | preSharedKey | string | Yes| No| PSK of the hotspot.|
| isHiddenSsid | boolean | Read only| Whether the network is hidden.| | isHiddenSsid | boolean | Yes| No| Whether the network is hidden.|
| securityType | [WifiSecurityType](#wifisecuritytype) | Read only| Security type.| | securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.|
| creatorUid | number | Read only| ID of the creator.<br> **System API**: This is a system API.| | creatorUid | number | Yes| No| ID of the creator.<br> **System API**: This is a system API.|
| disableReason | number | Read only| Reason for disabling WLAN.<br> **System API**: This is a system API.| | disableReason | number | Yes| No| Reason for disabling WLAN.<br> **System API**: This is a system API.|
| netId | number | Read only| Network ID.<br> **System API**: This is a system API.| | netId | number | Yes| No| Network ID.<br> **System API**: This is a system API.|
| randomMacType | number | Read only| Random MAC type.<br> **System API**: This is a system API.| | randomMacType | number | Yes| No| Random MAC type.<br> **System API**: This is a system API.|
| randomMacAddr | string | Read only| Random MAC address.<br> **System API**: This is a system API.| | randomMacAddr | string | Yes| No| Random MAC address.<br> **System API**: This is a system API.|
| ipType | [IpType](#iptype7) | Read only| IP address type.<br> **System API**: This is a system API.| | ipType | [IpType](#iptype7) | Yes| No| IP address type.<br> **System API**: This is a system API.|
| staticIp | [IpConfig](#ipconfig7) | Read only| Static IP address configuration.<br> **System API**: This is a system API.| | staticIp | [IpConfig](#ipconfig7) | Yes| No| Static IP address configuration.<br> **System API**: This is a system API.|
| eapConfig<sup>9+</sup> | [WifiEapConfig](#wifieapconfig9) | Read only| EAP configuration.<br> **System API**: This is a system API.|
## IpType<sup>7+</sup> ## IpType<sup>7+</sup>
Enumerates the IP address types. Enumerate the IP address types.
**System API**: This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.STA **System capability**: SystemCapability.Communication.WiFi.STA
| Name| Default Value| Description| | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| STATIC | 0 | Static IP address.| | STATIC | 0 | Static IP address.|
| DHCP | 1 | IP address allocated by DHCP.| | DHCP | 1 | IP address allocated by DHCP.|
...@@ -324,78 +285,12 @@ Represents IP configuration information. ...@@ -324,78 +285,12 @@ Represents IP configuration information.
**System capability**: SystemCapability.Communication.WiFi.STA **System capability**: SystemCapability.Communication.WiFi.STA
| **Name**| **Type**| **Readable/Writable**| **Description**| | **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| ipAddress | number | Read only| IP address.| | ipAddress | number | Yes| No| IP address.|
| gateway | number | Read only| Gateway.| | gateway | number | Yes| No| Gateway.|
| dnsServers | number[] | Read only| Domain name server (DNS) information.| | dnsServers | number[] | Yes| No| Domain name server (DNS) information.|
| domains | Array&lt;string&gt; | Read only| Domain information.| | domains | Array&lt;string&gt; | Yes| No| Domain information.|
## WifiEapConfig<sup>9+</sup>
Represents EAP configuration information.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.STA
| **Name**| **Type**| **Readable/Writable**| **Description**|
| -------- | -------- | -------- | -------- |
| eapMethod | [EapMethod](#eapmethod9) | Read only| EAP authentication method.|
| phase2Method | [Phase2Method](#phase2method9) | Read only| Phase 2 authentication method.|
| identity | string | Read only| Identity Information.|
| anonymousIdentity | string | Read only| Anonymous identity.|
| password | string | Read only| Password.|
| caCertAliases | string | Read only| CA certificate alias.|
| caPath | string | Read only| CA certificate path.|
| clientCertAliases | string | Read only| Client certificate alias.|
| altSubjectMatch | string | Read only| A string to match the alternate subject.|
| domainSuffixMatch | string | Read only| A string to match the domain suffix.|
| realm | string | Read only| Realm for the passpoint credential.|
| plmn | string | Read only| Public land mobile network (PLMN) of the passpoint credential provider.|
| eapSubId | number | Read only| Sub-ID of the SIM card.|
## EapMethod<sup>9+</sup>
Enumerates the EAP authentication methods.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.STA
| Name| Default Value| Description|
| -------- | -------- | -------- |
| EAP_NONE | 0 | Not specified.|
| EAP_PEAP | 1 | PEAP.|
| EAP_TLS | 2 | TLS.|
| EAP_TTLS | 3 | TTLS.|
| EAP_PWD | 4 | Password.|
| EAP_SIM | 5 | SIM.|
| EAP_AKA | 6 | AKA.|
| EAP_AKA_PRIME | 7 | AKA Prime.|
| EAP_UNAUTH_TLS | 8 | UNAUTH TLS.|
## Phase2Method<sup>9+</sup>
Enumerates the Phase 2 authentication methods.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.STA
| Name| Default Value| Description|
| -------- | -------- | -------- |
| PHASE2_NONE | 0 | Not specified.|
| PHASE2_PAP | 1 | PAP.|
| PHASE2_MSCHAP | 2 | MS-CHAP.|
| PHASE2_MSCHAPV2 | 3 | MS-CHAPv2.|
| PHASE2_GTC | 4 | GTC .|
| PHASE2_SIM | 5 | SIM.|
| PHASE2_AKA | 6 | AKA.|
| PHASE2_AKA_PRIME | 7 | AKA Prime.|
## wifi.addDeviceConfig ## wifi.addDeviceConfig
...@@ -500,122 +395,6 @@ Removes the configuration of an untrusted network. This API uses an asynchronous ...@@ -500,122 +395,6 @@ Removes the configuration of an untrusted network. This API uses an asynchronous
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| | callback | AsyncCallback&lt;boolean&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.|
## wifi.addCandidateConfig<sup>9+</sup>
addCandidateConfig(config: WifiDeviceConfig): Promise&lt;number&gt;
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**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the network configuration ID.|
## wifi.addCandidateConfig<sup>9+</sup>
addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback&lt;number&gt;): 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**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback 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.|
## wifi.removeCandidateConfig<sup>9+</sup>
removeCandidateConfig(networkId: number): Promise&lt;void&gt;
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**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| networkId | number | Yes| ID of the network configuration to remove.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
## wifi.removeCandidateConfig<sup>9+</sup>
removeCandidateConfig(networkId: number, callback: AsyncCallback&lt;void&gt;): 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**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| networkId | number | Yes| ID of the network configuration to remove.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result. If the operation is successful, the value of **err** is **0**. If **err** is not **0**, an error has occurred.|
## wifi.getCandidateConfigs<sup>9+</sup>
getCandidateConfigs(): &nbsp;Array&lt;[WifiDeviceConfig](#wifideviceconfig)&gt;
Obtains candidate network configuration.
**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.WiFi.STA
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| &nbsp;Array&lt;[WifiDeviceConfig](#wifideviceconfig)&gt; | Candidate network configuration obtained.|
## wifi.connectToCandidateConfig<sup>9+</sup>
connectToCandidateConfig(networkId: number): void
Connects to a candidate network.
**Required permissions**: ohos.permission.SET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.STA
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| networkId | number | Yes| ID of the candidate network configuration.|
## wifi.connectToNetwork ## wifi.connectToNetwork
connectToNetwork(networkId: number): boolean connectToNetwork(networkId: number): boolean
...@@ -725,7 +504,7 @@ Obtains WLAN connection information. This API uses a promise to return the resul ...@@ -725,7 +504,7 @@ Obtains WLAN connection information. This API uses a promise to return the resul
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[WifiLinkedInfo](#wifilinkedinfo)&gt; | Promise used to return the WLAN connection information obtained.| | Promise&lt;[WifiLinkedInfo](#wifilinkedinfo)&gt; | Promise used to return the WLAN connection information.|
## wifi.getLinkedInfo ## wifi.getLinkedInfo
...@@ -770,24 +549,23 @@ Represents the WLAN connection information. ...@@ -770,24 +549,23 @@ Represents the WLAN connection information.
**System capability**: SystemCapability.Communication.WiFi.STA **System capability**: SystemCapability.Communication.WiFi.STA
| Name| Type| Readable/Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| | ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.|
| bssid | string | Read only| BSSID of the hotspot.| | bssid | string | Yes| No| BSSID of the hotspot.|
| networkId | number | Read only| Network configuration ID.<br> **System API**: This is a system API.| | networkId | number | Yes| No| Network configuration ID.<br> **System API**: This is a system API.|
| rssi | number | Read only| RSSI of the hotspot, in dBm.| | rssi | number | Yes| No| RSSI of the hotspot, in dBm.|
| band | number | Read only| Frequency band of the WLAN AP.| | band | number | Yes| No| Frequency band of the WLAN AP.|
| linkSpeed | number | Read only| Speed of the WLAN AP.| | linkSpeed | number | Yes| No| Speed of the WLAN AP.|
| frequency | number | Read only| Frequency of the WLAN AP.| | frequency | number | Yes| No| Frequency of the WLAN AP.|
| isHidden | boolean | Read only| Whether to hide the WLAN AP.| | isHidden | boolean | Yes| No| Whether to hide the WLAN AP.|
| isRestricted | boolean | Read only| Whether to restrict data volume at the WLAN AP.| | isRestricted | boolean | Yes| No| Whether to restrict data volume at the WLAN AP.|
| chload | number | Read only| Channel load. A larger value indicates a higher load.<br> **System API**: This is a system API.| | chload | number | Yes| No| Channel load. A larger value indicates a higher load.<br> **System API**: This is a system API.|
| snr | number | Read only| Signal-to-noise ratio (SNR).<br> **System API**: This is a system API.| | snr | number | Yes| No| Signal-to-noise ratio (SNR).<br> **System API**: This is a system API.|
| macType<sup>9+</sup> | number | Read only| MAC address type.| | macAddress | string | Yes| No| MAC address of the device.|
| macAddress | string | Read only| MAC address of the device.| | ipAddress | number | Yes| No| IP address of the device that sets up the WLAN connection.|
| ipAddress | number | Read only| IP address of the device that sets up the WLAN connection.| | suppState | [SuppState](#suppstate) | Yes| No| Supplicant state.<br> **System API**: This is a system API.|
| suppState | [SuppState](#suppstate) | Read only| Supplicant state.<br> **System API**: This is a system API.| | connState | [ConnState](#connstate) | Yes| No| WLAN connection state.|
| connState | [ConnState](#connstate) | Read only| WLAN connection state.|
## ConnState ## ConnState
...@@ -796,7 +574,7 @@ Enumerates the WLAN connection states. ...@@ -796,7 +574,7 @@ Enumerates the WLAN connection states.
**System capability**: SystemCapability.Communication.WiFi.STA **System capability**: SystemCapability.Communication.WiFi.STA
| Name| Default Value| Description| | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| SCANNING | 0 | The device is scanning for available APs.| | SCANNING | 0 | The device is scanning for available APs.|
| CONNECTING | 1 | A WLAN connection is being established.| | CONNECTING | 1 | A WLAN connection is being established.|
...@@ -816,7 +594,7 @@ Enumerates the supplicant states. ...@@ -816,7 +594,7 @@ Enumerates the supplicant states.
**System capability**: SystemCapability.Communication.WiFi.STA **System capability**: SystemCapability.Communication.WiFi.STA
| Name| Default Value| Description| | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| DISCONNECTED | 0 | The supplicant is disconnected from the AP.| | DISCONNECTED | 0 | The supplicant is disconnected from the AP.|
| INTERFACE_DISABLED | 1 | The network interface is disabled.| | INTERFACE_DISABLED | 1 | The network interface is disabled.|
...@@ -871,16 +649,16 @@ Obtains the features supported by this device. ...@@ -871,16 +649,16 @@ Obtains the features supported by this device.
| Value| Description| | Value| Description|
| -------- | -------- | | -------- | -------- |
| 0x0001 | WLAN infrastructure mode. | | 0x0001 | WLAN infrastructure mode|
| 0x0002 | 5 GHz feature. | | 0x0002 | 5 GHz feature|
| 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature. | | 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature|
| 0x0008 | Wi-Fi Direct. | | 0x0008 | Wi-Fi Direct|
| 0x0010 | SoftAP. | | 0x0010 | SoftAP|
| 0x0040 | Wi-Fi AWare. | | 0x0040 | Wi-Fi AWare|
| 0x8000 | WLAN AP/STA concurrency. | | 0x8000 | WLAN AP/STA concurrency|
| 0x8000000 | WPA3 Personal (WPA-3 SAE). | | 0x8000000 | WPA3 Personal (WPA-3 SAE)|
| 0x10000000 | WPA3-Enterprise Suite B. | | 0x10000000 | WPA3-Enterprise Suite B |
| 0x20000000 | Enhanced open feature. | | 0x20000000 | Enhanced open feature|
## wifi.isFeatureSupported<sup>7+</sup> ## wifi.isFeatureSupported<sup>7+</sup>
...@@ -949,15 +727,15 @@ Represents IP information. ...@@ -949,15 +727,15 @@ Represents IP information.
**System capability**: SystemCapability.Communication.WiFi.STA **System capability**: SystemCapability.Communication.WiFi.STA
| **Name**| **Type**| **Readable/Writable**| **Description**| | **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| ipAddress | number | Read only| IP address.| | ipAddress | number | Yes| No| IP address.|
| gateway | number | Read only| Gateway.| | gateway | number | Yes| No| Gateway.|
| netmask | number | Read only| Subnet mask.| | netmask | number | Yes| No| Subnet mask.|
| primaryDns | number | Read only| IP address of the preferred DNS server.| | primaryDns | number | Yes| No| IP address of the preferred DNS server.|
| secondDns | number | Read only| IP address of the alternate DNS server.| | secondDns | number | Yes| No| IP address of the alternate DNS server.|
| serverIp | number | Read only| IP address of the DHCP server.| | serverIp | number | Yes| No| IP address of the DHCP server.|
| leaseDuration | number | Read only| Lease duration of the IP address.| | leaseDuration | number | Yes| No| Lease duration of the IP address.|
## wifi.getCountryCode<sup>7+</sup> ## wifi.getCountryCode<sup>7+</sup>
...@@ -1237,13 +1015,13 @@ Represents the hotspot configuration. ...@@ -1237,13 +1015,13 @@ Represents the hotspot configuration.
**System capability**: SystemCapability.Communication.WiFi.AP.Core **System capability**: SystemCapability.Communication.WiFi.AP.Core
| **Name**| **Type**| **Readable/Writable**| **Description**| | **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| | ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.|
| securityType | [WifiSecurityType](#wifisecuritytype) | Read only| Security type.| | securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.|
| band | number | Read only| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.| | band | number | Yes| No| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.|
| preSharedKey | string | Read only| PSK of the hotspot.| | preSharedKey | string | Yes| No| PSK of the hotspot.|
| maxConn | number | Read only| Maximum number of connections allowed.| | maxConn | number | Yes| No| Maximum number of connections allowed.|
## wifi.getHotspotConfig<sup>7+</sup> ## wifi.getHotspotConfig<sup>7+</sup>
...@@ -1292,11 +1070,11 @@ Represents the station information. ...@@ -1292,11 +1070,11 @@ Represents the station information.
**System capability**: SystemCapability.Communication.WiFi.AP.Core **System capability**: SystemCapability.Communication.WiFi.AP.Core
| **Name**| **Type**| **Readable/Writable**| **Description**| | **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| name | string | Read only| Device name.| | name | string | Yes| No| Device name.|
| macAddress | string | Read only| MAC address.| | macAddress | string | Yes| No| MAC address.|
| ipAddress | string | Read only| IP address.| | ipAddress | string | Yes| No| IP address.|
## wifi.getP2pLinkedInfo<sup>8+</sup> ## wifi.getP2pLinkedInfo<sup>8+</sup>
...@@ -1323,11 +1101,11 @@ Represents the P2P link information. ...@@ -1323,11 +1101,11 @@ Represents the P2P link information.
**System capability**: SystemCapability.Communication.WiFi.P2P **System capability**: SystemCapability.Communication.WiFi.P2P
| Name| Type| Readable/Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| connectState | [P2pConnectState](#p2pconnectstate8) | Read only| P2P connection state.| | connectState | [P2pConnectState](#p2pconnectstate8) | Yes| No| P2P connection state.|
| isGroupOwner | boolean | Read only| Whether the device is the group owner.| | isGroupOwner | boolean | Yes| No| Whether the device is the group owner.|
| groupOwnerAddr | string | Read only| MAC address of the group. | groupOwnerAddr | string | Yes| No| MAC address of the group.
## P2pConnectState<sup>8+</sup> ## P2pConnectState<sup>8+</sup>
...@@ -1336,7 +1114,7 @@ Enumerates the P2P connection states. ...@@ -1336,7 +1114,7 @@ Enumerates the P2P connection states.
**System capability**: SystemCapability.Communication.WiFi.P2P **System capability**: SystemCapability.Communication.WiFi.P2P
| Name| Default Value| Description| | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| DISCONNECTED | 0 | Disconnected.| | DISCONNECTED | 0 | Disconnected.|
| CONNECTED | 1 | Connected.| | CONNECTED | 1 | Connected.|
...@@ -1373,7 +1151,7 @@ Obtains the current P2P group information. This API uses a promise to return the ...@@ -1373,7 +1151,7 @@ Obtains the current P2P group information. This API uses a promise to return the
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[WifiP2pGroupInfo](#wifip2pgroupinfo8)&gt; | Promise used to return the group information obtained.| | Promise&lt;[WifiP2pGroupInfo](#wifip2pgroupinfo8)&gt; | Promise used to return the P2P group information obtained.|
## wifi.getCurrentGroup<sup>8+</sup> ## wifi.getCurrentGroup<sup>8+</sup>
...@@ -1433,13 +1211,13 @@ Represents the P2P device information. ...@@ -1433,13 +1211,13 @@ Represents the P2P device information.
**System capability**: SystemCapability.Communication.WiFi.P2P **System capability**: SystemCapability.Communication.WiFi.P2P
| Name| Type| Readable/Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| deviceName | string | Read only| Device name.| | deviceName | string | Yes| No| Device name.|
| deviceAddress | string | Read only| MAC address of the device.| | deviceAddress | string | Yes| No| MAC address of the device.|
| primaryDeviceType | string | Read only| Type of the primary device.| | primaryDeviceType | string | Yes| No| Type of the primary device.|
| deviceStatus | [P2pDeviceStatus](#p2pdevicestatus8) | Read only| Device status.| | deviceStatus | [P2pDeviceStatus](#p2pdevicestatus8) | Yes| No| Device status.|
| groupCapabilitys | number | Read only| Group capabilities.| | groupCapabilitys | number | Yes| No| Group capabilities.|
## P2pDeviceStatus<sup>8+</sup> ## P2pDeviceStatus<sup>8+</sup>
...@@ -1448,7 +1226,7 @@ Enumerates the P2P device states. ...@@ -1448,7 +1226,7 @@ Enumerates the P2P device states.
**System capability**: SystemCapability.Communication.WiFi.P2P **System capability**: SystemCapability.Communication.WiFi.P2P
| Name| Default Value| Description| | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| CONNECTED | 0 | Connected.| | CONNECTED | 0 | Connected.|
| INVITED | 1 | Invited.| | INVITED | 1 | Invited.|
...@@ -1457,40 +1235,6 @@ Enumerates the P2P device states. ...@@ -1457,40 +1235,6 @@ Enumerates the P2P device states.
| UNAVAILABLE | 4 | Unavailable.| | UNAVAILABLE | 4 | Unavailable.|
## wifi.getP2pLocalDevice<sup>9+</sup>
getP2pLocalDevice(): Promise&lt;WifiP2pDevice&gt;
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**
| Type| Description|
| -------- | -------- |
| Promise&lt;[WifiP2pDevice](#wifip2pdevice8)&gt; | Promise used to return the local device information obtained.|
## wifi.getP2pLocalDevice<sup>9+</sup>
getP2pLocalDevice(callback: AsyncCallback&lt;WifiP2pDevice&gt;): 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**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[WifiP2pDevice](#wifip2pdevice8)&gt; | Yes| Callback 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.|
## wifi.createGroup<sup>8+</sup> ## wifi.createGroup<sup>8+</sup>
createGroup(config: WifiP2PConfig): boolean createGroup(config: WifiP2PConfig): boolean
...@@ -1520,13 +1264,13 @@ Represents P2P group configuration. ...@@ -1520,13 +1264,13 @@ Represents P2P group configuration.
**System capability**: SystemCapability.Communication.WiFi.P2P **System capability**: SystemCapability.Communication.WiFi.P2P
| Name| Type| Readable/Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| deviceAddress | string | Read only| Device address.| | deviceAddress | string | Yes| No| Device address.|
| netId | number | Read only| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.| | netId | number | Yes| No| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.|
| passphrase | string | Read only| Passphrase of the group.| | passphrase | string | Yes| No| Passphrase of the group.|
| groupName | string | Read only| Name of the group.| | groupName | string | Yes| No| Name of the group.|
| goBand | [GroupOwnerBand](#groupownerband8) | Read only| Frequency band of the group.| | goBand | [GroupOwnerBand](#groupownerband8) | Yes| No| Frequency band of the group.|
## GroupOwnerBand<sup>8+</sup> ## GroupOwnerBand<sup>8+</sup>
...@@ -1535,7 +1279,7 @@ Enumerates the P2P group frequency bands. ...@@ -1535,7 +1279,7 @@ Enumerates the P2P group frequency bands.
**System capability**: SystemCapability.Communication.WiFi.P2P **System capability**: SystemCapability.Communication.WiFi.P2P
| Name| Default Value| Description| | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| GO_BAND_AUTO | 0 | Auto.| | GO_BAND_AUTO | 0 | Auto.|
| GO_BAND_2GHZ | 1 | 2 GHz.| | GO_BAND_2GHZ | 1 | 2 GHz.|
...@@ -1727,61 +1471,23 @@ Deletes a persistent group. ...@@ -1727,61 +1471,23 @@ Deletes a persistent group.
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.getP2pGroups<sup>9+</sup>
getP2pGroups(): Promise&lt;Array&lt;WifiP2pGroupInfo&gt;&gt;
Obtains information about all P2P groups. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.WiFi.P2P
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;&nbsp;Array&lt;[WifiP2pGroupInfo](#wifip2pgroupinfo8)&gt;&nbsp;&gt; | Promise used to return the group information obtained.|
## WifiP2pGroupInfo<sup>8+</sup> ## WifiP2pGroupInfo<sup>8+</sup>
Represents the P2P group information. Represents the P2P group information.
**System capability**: SystemCapability.Communication.WiFi.P2P **System capability**: SystemCapability.Communication.WiFi.P2P
| Name| Type| Readable/Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| isP2pGo | boolean | Read only| Whether the device is the group owner.| | isP2pGo | boolean | Yes| No| Whether the device is the group owner.|
| ownerInfo | [WifiP2pDevice](#wifip2pdevice8) | Read only| Device information of the group.| | ownerInfo | [WifiP2pDevice](#wifip2pdevice8) | Yes| No| Device information of the group.|
| passphrase | string | Read only| Passphrase of the group.| | passphrase | string | Yes| No| Passphrase of the group.|
| interface | string | Read only| Interface name.| | interface | string | Yes| No| Interface name.|
| groupName | string | Read only| Group name.| | groupName | string | Yes| No| Group name.|
| networkId | number | Read only| Network ID.| | networkId | number | Yes| No| Network ID.|
| frequency | number | Read only| Frequency of the group.| | frequency | number | Yes| No| Frequency of the group.|
| clientDevices | [WifiP2pDevice[]](#wifip2pdevice8) | Read only| List of connected devices.| | clientDevices | [WifiP2pDevice[]](#wifip2pdevice8) | Yes| No| List of connected devices.|
| goIpAddress | string | Read only| IP address of the group.| | goIpAddress | string | Yes| No| IP address of the group.|
## wifi.getP2pGroups<sup>9+</sup>
getP2pGroups(callback: AsyncCallback&lt;Array&lt;WifiP2pGroupInfo&gt;&gt;): 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**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;&nbsp;Array&lt;[WifiP2pGroupInfo](#wifip2pgroupinfo8)&gt;&gt; | Yes| Callback 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.|
## wifi.setDeviceName<sup>8+</sup> ## wifi.setDeviceName<sup>8+</sup>
...@@ -1830,10 +1536,10 @@ Registers the WLAN state change events. ...@@ -1830,10 +1536,10 @@ Registers the WLAN state change events.
| **Value**| **Description**| | **Value**| **Description**|
| -------- | -------- | | -------- | -------- |
| 0 | Deactivated. | | 0 | Deactivated|
| 1 | Activated. | | 1 | Activated|
| 2 | Activating. | | 2 | Activating|
| 3 | Deactivating. | | 3 | Deactivating|
## wifi.off('wifiStateChange')<sup>7+</sup> ## wifi.off('wifiStateChange')<sup>7+</sup>
...@@ -2012,10 +1718,10 @@ Registers the hotspot state change events. ...@@ -2012,10 +1718,10 @@ Registers the hotspot state change events.
| **Value**| **Description**| | **Value**| **Description**|
| -------- | -------- | | -------- | -------- |
| 0 | Deactivated. | | 0 | Deactivated|
| 1 | Activated. | | 1 | Activated|
| 2 | Activating. | | 2 | Activating|
| 3 | Deactivating. | | 3 | Deactivating|
## wifi.off('hotspotStateChange')<sup>7+</sup> ## wifi.off('hotspotStateChange')<sup>7+</sup>
...@@ -2057,11 +1763,11 @@ Registers the P2P state change events. ...@@ -2057,11 +1763,11 @@ Registers the P2P state change events.
| **Value**| **Description**| | **Value**| **Description**|
| -------- | -------- | | -------- | -------- |
| 1 | Available. | | 1 | Available|
| 2 | Opening. | | 2 | Opening|
| 3 | Opened. | | 3 | Opened|
| 4 | Closing. | | 4 | Closing|
| 5 | Closed. | | 5 | Closed|
## wifi.off('p2pStateChange')<sup>8+</sup> ## wifi.off('p2pStateChange')<sup>8+</sup>
......
# 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 other 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
```js
import wifiManager from '@ohos.wifiManager';
```
## wifi.enableWifi<sup>9+</sup>
enableWifi(): void
Enables WLAN.
**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
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.disableWifi<sup>9+</sup>
disableWifi(): void
Disables WLAN.
**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
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.isWifiActive<sup>9+</sup>
isWifiActive(): boolean
Checks whether WLAN is enabled.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.STA
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.|
## wifi.scan<sup>9+</sup>
scan(): void
Starts a scan for WLAN.
**Required permissions**: **ohos.permission.SET_WIFI_INFO** and **ohos.permission.LOCATION**
**System capability**: SystemCapability.Communication.WiFi.STA
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.getScanResults<sup>9+</sup>
getScanResults(): Promise&lt;Array&lt;WifiScanInfo&gt;&gt;
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)
**System capability**: SystemCapability.Communication.WiFi.STA
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| Promise&lt;&nbsp;Array&lt;[WifiScanInfo](#wifiscaninfo)&gt;&nbsp;&gt; | Promise used to return the detected hotspots.|
## wifi.getScanResults<sup>9+</sup>
getScanResults(callback: AsyncCallback&lt;Array&lt;WifiScanInfo&gt;&gt;): 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)
**System capability**: SystemCapability.Communication.WiFi.STA
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;&nbsp;Array&lt;[WifiScanInfo](#wifiscaninfo)&gt;&gt; | Yes| Callback 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.|
**Example**
```js
import wifi from '@ohos.wifi';
wifi.getScanInfos((err, result) => {
if (err) {
console.error("get scan info error");
return;
}
var len = Object.keys(result).length;
console.log("wifi received scan info: " + len);
for (var 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);
}
});
wifi.getScanInfos().then(result => {
var len = Object.keys(result).length;
console.log("wifi received scan info: " + len);
for (var 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);
}
});
```
## WifiScanInfo<sup>9+</sup>
Represents WLAN hotspot information.
**System capability**: SystemCapability.Communication.WiFi.STA
| **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | -------- |
| ssid | string | Yes| No| Service set identifier (SSID) of the hotspot, in UTF-8 format.|
| bssid | string | Yes| No| Basic service set identifier (BSSID) of the hotspot.|
| capabilities | string | Yes| No| Hotspot capabilities.|
| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| WLAN security type.|
| rssi | number | Yes| No| Received signal strength indicator (RSSI) of the hotspot, in dBm.|
| band | number | Yes| No| Frequency band of the WLAN access point (AP).|
| frequency | number | Yes| No| Frequency of the WLAN AP.|
| channelWidth | number | Yes| No| Channel width of the WLAN AP.|
| centerFrequency0 | number | Yes| No| Center frequency of the hotspot.|
| centerFrequency1 | number | Yes| No| Center frequency of the hotspot. If the hotspot uses two non-overlapping WLAN channels, two center frequencies, namely **centerFrequency0** and **centerFrequency1**, are returned.|
| infoElems | Array&lt;[WifiInfoElem](#wifiinfoelem9)&gt; | Yes| No| Information elements.|
| timestamp | number | Yes| No| Timestamp.|
## WifiSecurityType<sup>9+</sup>
Enumerates the WLAN security types.
**System capability**: SystemCapability.Communication.WiFi.Core
| **Name**| **Value**| **Description**|
| -------- | -------- | -------- |
| WIFI_SEC_TYPE_INVALID | 0 | Invalid security type.|
| WIFI_SEC_TYPE_OPEN | 1 | Open security type.|
| WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP).|
| WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK).|
| WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE).|
| WIFI_SEC_TYPE_EAP<sup>9+</sup> | 5 | Extensible Authentication protocol (EAP).|
| WIFI_SEC_TYPE_EAP_SUITE_B<sup>9+</sup> | 6 | Suite B 192-bit encryption.|
| WIFI_SEC_TYPE_OWE<sup>9+</sup> | 7 | Opportunistic Wireless Encryption (OWE).|
| WIFI_SEC_TYPE_WAPI_CERT<sup>9+</sup> | 8 | WLAN Authentication and Privacy Infrastructure (WAPI) in certificate-based mode (WAPI-CERT).|
| WIFI_SEC_TYPE_WAPI_PSK<sup>9+</sup> | 9 | WAPI-PSK.|
## WifiInfoElem<sup>9+</sup>
Represents a WLAN information element.
**System capability**: SystemCapability.Communication.WiFi.STA
| **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | -------- |
| eid | number | Yes| No| ID of the information element.|
| content | Uint8Array | Yes| No| Content of the information element.|
## WifiChannelWidth<sup>9+</sup>
Enumerates the WLAN channel widths.
**System capability**: SystemCapability.Communication.WiFi.STA
| **Name**| **Value**| **Description**|
| -------- | -------- | -------- |
| WIDTH_20MHZ | 0 | 20 MHz.|
| WIDTH_40MHZ | 1 | 40 MHz.|
| WIDTH_80MHZ | 2 | 80 MHz.|
| WIDTH_160MHZ | 3 | 160 MHz.|
| WIDTH_80MHZ_PLUS | 4 | 80 MHz<sup>+</sup>.|
| WIDTH_INVALID | 5 | Invalid value.|
## wifi.getScanResultsSync<sup>9+</sup>
getScanResultsSync(): &nbsp;Array&lt;[WifiScanInfo](#wifiscaninfo)&gt;
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)
**System capability**: SystemCapability.Communication.WiFi.STA
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| &nbsp;Array&lt;[WifiScanInfo](#wifiscaninfo)&gt; | Scan result obtained.|
## wifi.addDeviceConfig<sup>9+</sup>
addDeviceConfig(config: WifiDeviceConfig): Promise&lt;number&gt;
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**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the ID of the added network configuration. If **-1** is returned, the network configuration fails to be added.|
## WifiDeviceConfig<sup>9+</sup>
Represents the WLAN configuration.
**System capability**: SystemCapability.Communication.WiFi.STA
| **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | -------- |
| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.|
| bssid | string | Yes| No| BSSID of the hotspot.|
| preSharedKey | string | Yes| No| PSK of the hotspot.|
| isHiddenSsid | boolean | Yes| No| Whether the network is hidden.|
| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.|
| creatorUid | number | Yes| No| ID of the creator.<br> **System API**: This is a system API.|
| disableReason | number | Yes| No| Reason for disabling WLAN.<br> **System API**: This is a system API.|
| netId | number | Yes| No| Network ID.<br> **System API**: This is a system API.|
| randomMacType | number | Yes| No| Random MAC type.<br> **System API**: This is a system API.|
| randomMacAddr | string | Yes| No| Random MAC address.<br> **System API**: This is a system API.|
| ipType | [IpType](#iptype9) | Yes| No| IP address type.<br> **System API**: This is a system API.|
| staticIp | [IpConfig](#ipconfig9) | Yes| No| Static IP address configuration.<br> **System API**: This is a system API.|
| eapConfig<sup>9+</sup> | [WifiEapConfig](#wifieapconfig9) | Yes| No| EAP configuration.<br> **System API**: This is a system API.|
## IpType<sup>9+</sup>
Enumerates the IP address types.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.STA
| Name| Value| Description|
| -------- | -------- | -------- |
| STATIC | 0 | Static IP address.|
| DHCP | 1 | IP address allocated by DHCP.|
| UNKNOWN | 2 | Not specified.|
## IpConfig<sup>9+</sup>
Represents IP configuration information.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.STA
| **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | -------- |
| ipAddress | number | Yes| No| IP address.|
| gateway | number | Yes| No| Gateway.|
| prefixLength | number | Yes| No| Subnet mask.|
| dnsServers | number[] | Yes| No| Domain name server (DNS) information.|
| domains | Array&lt;string&gt; | Yes| No| Domain information.|
## WifiEapConfig<sup>9+</sup>
Represents EAP configuration information.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.STA
| **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | -------- |
| eapMethod | [EapMethod](#eapmethod9) | Yes| No| EAP authentication method.|
| phase2Method | [Phase2Method](#phase2method9) | Yes| No| Phase 2 authentication method.|
| identity | string | Yes| No| Identity Information.|
| anonymousIdentity | string | Yes| No| Anonymous identity.|
| password | string | Yes| No| Password.|
| caCertAliases | string | Yes| No| CA certificate alias.|
| caPath | string | Yes| No| CA certificate path.|
| clientCertAliases | string | Yes| No| Client certificate alias.|
| altSubjectMatch | string | Yes| No| A string to match the alternate subject.|
| domainSuffixMatch | string | Yes| No| A string to match the domain suffix.|
| realm | string | Yes| No| Realm for the passpoint credential.|
| plmn | string | Yes| No| Public land mobile network (PLMN) of the passpoint credential provider.|
| eapSubId | number | Yes| No| Sub-ID of the SIM card.|
## EapMethod<sup>9+</sup>
Enumerates the EAP authentication methods.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.STA
| Name| Value| Description|
| -------- | -------- | -------- |
| EAP_NONE | 0 | Not specified.|
| EAP_PEAP | 1 | PEAP.|
| EAP_TLS | 2 | TLS.|
| EAP_TTLS | 3 | TTLS.|
| EAP_PWD | 4 | Password.|
| EAP_SIM | 5 | SIM.|
| EAP_AKA | 6 | AKA.|
| EAP_AKA_PRIME | 7 | AKA Prime.|
| EAP_UNAUTH_TLS | 8 | UNAUTH TLS.|
## Phase2Method<sup>9+</sup>
Enumerates the Phase 2 authentication methods.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.STA
| Name| Value| Description|
| -------- | -------- | -------- |
| PHASE2_NONE | 0 | Not specified.|
| PHASE2_PAP | 1 | PAP.|
| PHASE2_MSCHAP | 2 | MS-CHAP.|
| PHASE2_MSCHAPV2 | 3 | MS-CHAPv2.|
| PHASE2_GTC | 4 | GTC .|
| PHASE2_SIM | 5 | SIM.|
| PHASE2_AKA | 6 | AKA.|
| PHASE2_AKA_PRIME | 7 | AKA Prime.|
## wifi.addDeviceConfig<sup>9+</sup>
addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback&lt;number&gt;): 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**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback 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.|
## wifi.addCandidateConfig<sup>9+</sup>
addCandidateConfig(config: WifiDeviceConfig): Promise&lt;number&gt;
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**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the network configuration ID.|
## wifi.addCandidateConfig<sup>9+</sup>
addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback&lt;number&gt;): 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**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback 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.|
## wifi.removeCandidateConfig<sup>9+</sup>
removeCandidateConfig(networkId: number): Promise&lt;void&gt;
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**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| networkId | number | Yes| ID of the network configuration to remove.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
## wifi.removeCandidateConfig<sup>9+</sup>
removeCandidateConfig(networkId: number, callback: AsyncCallback&lt;void&gt;): 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**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| networkId | number | Yes| ID of the network configuration to remove.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result. If the operation is successful, the value of **err** is **0**. If **err** is not **0**, an error has occurred.|
## wifi.getCandidateConfigs<sup>9+</sup>
getCandidateConfigs(): &nbsp;Array&lt;[WifiDeviceConfig](#wifideviceconfig)&gt;
Obtains candidate network configuration.
**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.WiFi.STA
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| &nbsp;Array&lt;[WifiDeviceConfig](#wifideviceconfig)&gt; | Candidate network configuration obtained.|
## wifi.connectToCandidateConfig<sup>9+</sup>
connectToCandidateConfig(networkId: number): void
Connects to a candidate network.
**Required permissions**: ohos.permission.SET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.STA
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| networkId | number | Yes| ID of the candidate network configuration.|
## wifi.connectToNetwork<sup>9+</sup>
connectToNetwork(networkId: number): void
Connects to the specified network.
**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**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| networkId | number | Yes| Network configuration ID.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.connectToDevice<sup>9+</sup>
connectToDevice(config: WifiDeviceConfig): void
Connects to the specified network.
**System API**: This is a system API.
**Required permissions**: ohos.permission.SET_WIFI_INFO, ohos.permission.SET_WIFI_CONFIG, and ohos.permissio.MANAGE_WIFI_CONNECTION (available only to system applications)
**System capability**:
SystemCapability.Communication.WiFi.STA
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.disconnect<sup>9+</sup>
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
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.getSignalLevel<sup>9+</sup>
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**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| rssi | number | Yes| RSSI of the hotspot, in dBm.|
| band | number | Yes| Frequency band of the WLAN AP.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| number | Signal level obtained. The value range is [0, 4].|
## wifi.getLinkedInfo<sup>9+</sup>
getLinkedInfo(): Promise&lt;WifiLinkedInfo&gt;
Obtains WLAN connection information. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.STA
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[WifiLinkedInfo](#wifilinkedinfo)&gt; | Promise used to return the WLAN connection information obtained.|
## wifi.getLinkedInfo<sup>9+</sup>
getLinkedInfo(callback: AsyncCallback&lt;WifiLinkedInfo&gt;): void
Obtains WLAN connection information. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.STA
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[WifiLinkedInfo](#wifilinkedinfo)&gt; | Yes| Callback 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.|
**Example**
```js
import wifi from '@ohos.wifi';
wifi.getLinkedInfo((err, data) => {
if (err) {
console.error("get linked info error");
return;
}
console.info("get wifi linked info: " + JSON.stringify(data));
});
wifi.getLinkedInfo().then(data => {
console.info("get wifi linked info: " + JSON.stringify(data));
}).catch(error => {
console.info("get linked info error");
});
```
## WifiLinkedInfo<sup>9+</sup>
Represents the WLAN connection information.
**System capability**: SystemCapability.Communication.WiFi.STA
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.|
| bssid | string | Yes| No| BSSID of the hotspot.|
| networkId | number | Yes| No| Network configuration ID.<br> **System API**: This is a system API.|
| rssi | number | Yes| No| RSSI of the hotspot, in dBm.|
| band | number | Yes| No| Frequency band of the WLAN AP.|
| linkSpeed | number | Yes| No| Speed of the WLAN AP.|
| frequency | number | Yes| No| Frequency of the WLAN AP.|
| isHidden | boolean | Yes| No| Whether to hide the WLAN AP.|
| isRestricted | boolean | Yes| No| Whether to restrict data volume at the WLAN AP.|
| chload | number | Yes| No| Channel load. A larger value indicates a higher load.<br> **System API**: This is a system API.|
| snr | number | Yes| No| Signal-to-noise ratio (SNR).<br> **System API**: This is a system API.|
| macType<sup>9+</sup> | number | Yes| No| MAC address type.|
| macAddress | string | Yes| No| MAC address of the device.|
| ipAddress | number | Yes| No| IP address of the device that sets up the WLAN connection.|
| suppState | [SuppState](#suppstate) | Yes| No| Supplicant state.<br> **System API**: This is a system API.|
| connState | [ConnState](#connstate) | Yes| No| WLAN connection state.|
## ConnState<sup>9+</sup>
Enumerates the WLAN connection states.
**System capability**: SystemCapability.Communication.WiFi.STA
| Name| Value| Description|
| -------- | -------- | -------- |
| SCANNING | 0 | The device is scanning for available APs.|
| CONNECTING | 1 | A WLAN connection is being established.|
| AUTHENTICATING | 2 | An authentication is being performed for a WLAN connection.|
| OBTAINING_IPADDR | 3 | The IP address of the WLAN connection is being acquired.|
| CONNECTED | 4 | A WLAN connection is established.|
| DISCONNECTING | 5 | The WLAN connection is being disconnected.|
| DISCONNECTED | 6 | The WLAN connection is disconnected.|
| UNKNOWN | 7 | Failed to set up the WLAN connection.|
## SuppState<sup>9+</sup>
Enumerates the supplicant states.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.STA
| Name| Value| Description|
| -------- | -------- | -------- |
| DISCONNECTED | 0 | The supplicant is disconnected from the AP.|
| INTERFACE_DISABLED | 1 | The network interface is disabled.|
| INACTIVE | 2 | The supplicant is inactive.|
| SCANNING | 3 | The supplicant is scanning for a WLAN connection.|
| AUTHENTICATING | 4 | The supplicant is being authenticated.|
| ASSOCIATING | 5 | The supplicant is being associated with an AP.|
| ASSOCIATED | 6 | The supplicant is associated with an AP.|
| FOUR_WAY_HANDSHAKE | 7 | A four-way handshake is being performed for the supplicant.|
| GROUP_HANDSHAKE | 8 | A group handshake is being performed for the supplicant.|
| COMPLETED | 9 | The authentication is complete.|
| UNINITIALIZED | 10 | The supplicant failed to set up the connection.|
| INVALID | 11 | Invalid value.|
## wifi.isConnected<sup>9+</sup>
isConnected(): boolean
Checks whether the WLAN is connected.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.STA
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.|
## wifi.getSupportedFeatures<sup>9+</sup>
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**
| **Type**| **Description**|
| -------- | -------- |
| number | Feature value. |
**Feature IDs**
| Value| Description|
| -------- | -------- |
| 0x0001 | WLAN infrastructure mode|
| 0x0002 | 5 GHz feature|
| 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature|
| 0x0008 | Wi-Fi Direct|
| 0x0010 | SoftAP|
| 0x0040 | Wi-Fi AWare|
| 0x8000 | WLAN AP/STA concurrency|
| 0x8000000 | WPA3 Personal (WPA-3 SAE)|
| 0x10000000 | WPA3-Enterprise Suite B |
| 0x20000000 | Enhanced open feature|
## wifi.isFeatureSupported<sup>9+</sup>
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**
| **Name**| **Type**| Mandatory| **Description**|
| -------- | -------- | -------- | -------- |
| featureId | number | Yes| Feature ID.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the feature is supported; returns **false** otherwise.|
## wifi.getDeviceMacAddress<sup>9+</sup>
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**
| **Type**| **Description**|
| -------- | -------- |
| string[] | MAC address obtained.|
## wifi.getIpInfo<sup>9+</sup>
getIpInfo(): IpInfo
Obtains IP information.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.STA
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| [IpInfo](#ipinfo9) | IP information obtained.|
## IpInfo<sup>9+</sup>
Represents IP information.
**System capability**: SystemCapability.Communication.WiFi.STA
| **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | -------- |
| ipAddress | number | Yes| No| IP address.|
| gateway | number | Yes| No| Gateway.|
| netmask | number | Yes| No| Subnet mask.|
| primaryDns | number | Yes| No| IP address of the preferred DNS server.|
| secondDns | number | Yes| No| IP address of the alternate DNS server.|
| serverIp | number | Yes| No| IP address of the DHCP server.|
| leaseDuration | number | Yes| No| Lease duration of the IP address.|
## wifi.getCountryCode<sup>9+</sup>
getCountryCode(): string
Obtains the country code.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.Core
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| string | Country code obtained.|
## wifi.reassociate<sup>9+</sup>
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
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.reconnect<sup>9+</sup>
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
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.getDeviceConfigs<sup>9+</sup>
getDeviceConfigs(): &nbsp;Array&lt;[WifiDeviceConfig](#wifideviceconfig)&gt;
Obtains network configuration.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.GET_WIFI_CONFIG
**System capability**: SystemCapability.Communication.WiFi.STA
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| &nbsp;Array&lt;[WifiDeviceConfig](#wifideviceconfig)&gt; | Array of network configuration obtained.|
## wifi.updateNetwork<sup>9+</sup>
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**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| New WLAN configuration.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.|
## wifi.disableNetwork<sup>9+</sup>
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**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| netId | number | Yes| ID of the network configuration to disable.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.removeAllNetwork<sup>9+</sup>
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
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.removeDevice<sup>9+</sup>
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**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| id | number | Yes| ID of the network configuration to remove.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.enableHotspot<sup>9+</sup>
enableHotspot(): void
Enables this hotspot.
**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
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.disableHotspot<sup>9+</sup>
disableHotspot(): void
Disables this hotspot.
**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
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.isHotspotDualBandSupported<sup>9+</sup>
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**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the feature is supported; returns **false** otherwise.|
## wifi.isHotspotActive<sup>9+</sup>
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**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the hotspot is active; returns **false** otherwise.|
## wifi.setHotspotConfig<sup>9+</sup>
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**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| config | [HotspotConfig](#hotspotconfig9) | Yes| Hotspot configuration to set.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## HotspotConfig<sup>9+</sup>
Represents the hotspot configuration.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.AP.Core
| **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | -------- |
| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.|
| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.|
| band | number | Yes| No| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.|
| preSharedKey | string | Yes| No| PSK of the hotspot.|
| maxConn | number | Yes| No| Maximum number of connections allowed.|
## wifi.getHotspotConfig<sup>9+</sup>
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**
| **Type**| **Description**|
| -------- | -------- |
| [HotspotConfig](#hotspotconfig9) | Hotspot configuration obtained.|
## wifi.getStations<sup>9+</sup>
getStations(): &nbsp;Array&lt;[StationInfo](#stationinfo9)&gt;
Obtains information about the connected stations.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications)
**System capability**: SystemCapability.Communication.WiFi.AP.Core
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| &nbsp;Array&lt;[StationInfo](#stationinfo9)&gt; | Connected stations obtained.|
## StationInfo<sup>9+</sup>
Represents the station information.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.AP.Core
| **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | -------- |
| name | string | Yes| No| Device name.|
| macAddress | string | Yes| No| MAC address.|
| ipAddress | string | Yes| No| IP address.|
## wifi.getP2pLinkedInfo<sup>9+</sup>
getP2pLinkedInfo(): Promise&lt;WifiP2pLinkedInfo&gt;
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**
| Type| Description|
| -------- | -------- |
| Promise&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo9)&gt; | Promise used to return the P2P link information obtained.|
## WifiP2pLinkedInfo<sup>9+</sup>
Represents the P2P link information.
**System capability**: SystemCapability.Communication.WiFi.P2P
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| connectState | [P2pConnectState](#p2pconnectstate9) | Yes| No| P2P connection state.|
| isGroupOwner | boolean | Yes| No| Whether the device is the group owner.|
| groupOwnerAddr | string | Yes| No| MAC address of the group.
## P2pConnectState<sup>9+</sup>
Enumerates the P2P connection states.
**System capability**: SystemCapability.Communication.WiFi.P2P
| Name| Value| Description|
| -------- | -------- | -------- |
| DISCONNECTED | 0 | Disconnected.|
| CONNECTED | 1 | Connected.|
## wifi.getP2pLinkedInfo<sup>9+</sup>
getP2pLinkedInfo(callback: AsyncCallback&lt;WifiP2pLinkedInfo&gt;): 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**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo9)&gt; | Yes| Callback 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.|
## wifi.getCurrentGroup<sup>9+</sup>
getCurrentGroup(): Promise&lt;WifiP2pGroupInfo&gt;
Obtains the current P2P group information. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.WiFi.P2P
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[WifiP2pGroupInfo](#wifip2pgroupinfo9)&gt; | Promise used to return the P2P group information obtained.|
## wifi.getCurrentGroup<sup>9+</sup>
getCurrentGroup(callback: AsyncCallback&lt;WifiP2pGroupInfo&gt;): void
Obtains the current P2P group information. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[WifiP2pGroupInfo](#wifip2pgroupinfo9)&gt; | Yes| Callback 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.|
## wifi.getP2pPeerDevices<sup>9+</sup>
getP2pPeerDevices(): Promise&lt;WifiP2pDevice[]&gt;
Obtains the peer device list in the P2P connection. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.WiFi.P2P
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[WifiP2pDevice[]](#wifip2pdevice9)&gt; | Promise used to return the peer device list.|
## wifi.getP2pPeerDevices<sup>9+</sup>
getP2pPeerDevices(callback: AsyncCallback&lt;WifiP2pDevice[]&gt;): void
Obtains the peer device list in the P2P connection. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[WifiP2pDevice[]](#wifip2pdevice9)&gt; | Yes| Callback 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.|
## WifiP2pDevice<sup>9+</sup>
Represents the P2P device information.
**System capability**: SystemCapability.Communication.WiFi.P2P
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| deviceName | string | Yes| No| Device name.|
| deviceAddress | string | Yes| No| MAC address of the device.|
| primaryDeviceType | string | Yes| No| Type of the primary device.|
| deviceStatus | [P2pDeviceStatus](#p2pdevicestatus9) | Yes| No| Device status.|
| groupCapabilities | number | Yes| No| Group capabilities.|
## P2pDeviceStatus<sup>9+</sup>
Enumerates the P2P device states.
**System capability**: SystemCapability.Communication.WiFi.P2P
| Name| Value| Description|
| -------- | -------- | -------- |
| CONNECTED | 0 | Connected.|
| INVITED | 1 | Invited.|
| FAILED | 2 | Failed.|
| AVAILABLE | 3 | Available.|
| UNAVAILABLE | 4 | Unavailable.|
## wifi.getP2pLocalDevice<sup>9+</sup>
getP2pLocalDevice(): Promise&lt;WifiP2pDevice&gt;
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**
| Type| Description|
| -------- | -------- |
| Promise&lt;[WifiP2pDevice](#wifip2pdevice9)&gt; | Promise used to return the local device information obtained.|
## wifi.getP2pLocalDevice<sup>9+</sup>
getP2pLocalDevice(callback: AsyncCallback&lt;WifiP2pDevice&gt;): 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**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[WifiP2pDevice](#wifip2pdevice9)&gt; | Yes| Callback 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.|
## wifi.createGroup<sup>9+</sup>
createGroup(config: WifiP2PConfig): void
Creates a P2P group.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| **Name**| **Type**| Mandatory| **Description**|
| -------- | -------- | -------- | -------- |
| config | [WifiP2PConfig](#wifip2pconfig9) | Yes| Group configuration.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## WifiP2PConfig<sup>9+</sup>
Represents P2P group configuration.
**System capability**: SystemCapability.Communication.WiFi.P2P
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| deviceAddress | string | Yes| No| Device address.|
| netId | number | Yes| No| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.|
| passphrase | string | Yes| No| Passphrase of the group.|
| groupName | string | Yes| No| Name of the group.|
| goBand | [GroupOwnerBand](#groupownerband9) | Yes| No| Frequency band of the group.|
## GroupOwnerBand<sup>9+</sup>
Enumerates the P2P group frequency bands.
**System capability**: SystemCapability.Communication.WiFi.P2P
| Name| Value| Description|
| -------- | -------- | -------- |
| GO_BAND_AUTO | 0 | Auto.|
| GO_BAND_2GHZ | 1 | 2 GHz.|
| GO_BAND_5GHZ | 2 | 5 GHz.|
## wifi.removeGroup<sup>9+</sup>
removeGroup(): void
Removes this P2P group.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.P2P
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.p2pConnect<sup>9+</sup>
p2pConnect(config: WifiP2PConfig): void
Sets up a P2P connection.
**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| **Name**| **Type**| Mandatory| **Description**|
| -------- | -------- | -------- | -------- |
| config | [WifiP2PConfig](#wifip2pconfig9) | Yes| P2P group configuration.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```js
import wifi from '@ohos.wifi';
var recvP2pConnectionChangeFunc = result => {
console.info("p2p connection change receive event: " + JSON.stringify(result));
wifi.getP2pLinkedInfo((err, data) => {
if (err) {
console.error('failed to get getP2pLinkedInfo: ' + JSON.stringify(err));
return;
}
console.info("get getP2pLinkedInfo: " + JSON.stringify(data));
});
}
wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc);
var recvP2pDeviceChangeFunc = result => {
console.info("p2p device change receive event: " + JSON.stringify(result));
}
wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc);
var recvP2pPeerDeviceChangeFunc = result => {
console.info("p2p peer device change receive event: " + JSON.stringify(result));
wifi.getP2pPeerDevices((err, data) => {
if (err) {
console.error('failed to get peer devices: ' + JSON.stringify(err));
return;
}
console.info("get peer devices: " + JSON.stringify(data));
var len = Object.keys(data).length;
for (var i = 0; i < len; ++i) {
if (data[i].deviceName === "my_test_device") {
console.info("p2p connect to test device: " + data[i].deviceAddress);
var config = {
"deviceAddress":data[i].deviceAddress,
"netId":-2,
"passphrase":"",
"groupName":"",
"goBand":0,
}
wifi.p2pConnect(config);
}
}
});
}
wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);
var recvP2pPersistentGroupChangeFunc = () => {
console.info("p2p persistent group change receive event");
wifi.getCurrentGroup((err, data) => {
if (err) {
console.error('failed to get current group: ' + JSON.stringify(err));
return;
}
console.info("get current group: " + JSON.stringify(data));
});
}
wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);
setTimeout(function() {wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000);
setTimeout(function() {wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000);
setTimeout(function() {wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000);
setTimeout(function() {wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000);
console.info("start discover devices -> " + wifi.startDiscoverDevices());
```
## wifi.p2pCancelConnect<sup>9+</sup>
p2pCancelConnect(): void
Cancels this P2P connection.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.P2P
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.startDiscoverDevices<sup>9+</sup>
startDiscoverDevices(): void
Starts to discover devices.
**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.WiFi.P2P
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.stopDiscoverDevices<sup>9+</sup>
stopDiscoverDevices(): void
Stops discovering devices.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.P2P
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.deletePersistentGroup<sup>9+</sup>
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**
| **Name**| **Type**| Mandatory| **Description**|
| -------- | -------- | -------- | -------- |
| netId | number | Yes| ID of the group to delete.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.getP2pGroups<sup>9+</sup>
getP2pGroups(): Promise&lt;Array&lt;WifiP2pGroupInfo&gt;&gt;
Obtains information about all P2P groups. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.WiFi.P2P
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;&nbsp;Array&lt;[WifiP2pGroupInfo](#wifip2pgroupinfo9)&gt;&nbsp;&gt; | Promise used to return the group information obtained.|
## WifiP2pGroupInfo<sup>9+</sup>
Represents the P2P group information.
**System capability**: SystemCapability.Communication.WiFi.P2P
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| isP2pGo | boolean | Yes| No| Whether the device is the group owner.|
| ownerInfo | [WifiP2pDevice](#wifip2pdevice9) | Yes| No| Device information of the group.|
| passphrase | string | Yes| No| Passphrase of the group.|
| interface | string | Yes| No| Interface name.|
| groupName | string | Yes| No| Group name.|
| networkId | number | Yes| No| Network ID.|
| frequency | number | Yes| No| Frequency of the group.|
| clientDevices | [WifiP2pDevice[]](#wifip2pdevice9) | Yes| No| List of connected devices.|
| goIpAddress | string | Yes| No| IP address of the group.|
## wifi.getP2pGroups<sup>9+</sup>
getP2pGroups(callback: AsyncCallback&lt;Array&lt;WifiP2pGroupInfo&gt;&gt;): 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**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;&nbsp;Array&lt;[WifiP2pGroupInfo](#wifip2pgroupinfo9)&gt;&gt; | Yes| Callback 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.|
## wifi.setDeviceName<sup>9+</sup>
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**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| devName | string | Yes| Device name to set.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifi.on('wifiStateChange')<sup>9+</sup>
on(type: "wifiStateChange", callback: Callback&lt;number&gt;): void
Registers the WLAN state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.STA
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiStateChange**.|
| callback | Callback&lt;number&gt; | Yes| Callback invoked to return the WLAN state.|
**WLAN states**
| **Value**| **Description**|
| -------- | -------- |
| 0 | Deactivated|
| 1 | Activated|
| 2 | Activating|
| 3 | Deactivating|
## wifi.off('wifiStateChange')<sup>9+</sup>
off(type: "wifiStateChange", callback?: Callback&lt;number&gt;): void
Unregisters the WLAN state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.STA
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiStateChange**.|
| callback | Callback&lt;number&gt; | No| Callback for the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
**Example**
```js
import wifi from '@ohos.wifi';
var recvPowerNotifyFunc = result => {
console.info("Receive power state change event: " + result);
}
// Register an event.
wifi.on("wifiStateChange", recvPowerNotifyFunc);
// Unregister an event.
wifi.off("wifiStateChange", recvPowerNotifyFunc);
```
## wifi.on('wifiConnectionChange')<sup>7+</sup>
on(type: "wifiConnectionChange", callback: Callback&lt;number&gt;): void
Registers the WLAN connection state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.STA
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiConnectionChange**.|
| callback | Callback&lt;number&gt; | Yes| Callback invoked to return the WLAN connection state.|
**WLAN connection states**
| **Value**| **Description**|
| -------- | -------- |
| 0 | Disconnected.|
| 1 | Connected.|
## wifi.off('wifiConnectionChange')<sup>9+</sup>
off(type: "wifiConnectionChange", callback?: Callback&lt;number&gt;): void
Unregisters the WLAN connection state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.STA
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiConnectionChange**.|
| callback | Callback&lt;number&gt; | No| Callback for the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('wifiScanStateChange')<sup>9+</sup>
on(type: "wifiScanStateChange", callback: Callback&lt;number&gt;): void
Registers the WLAN scan state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.STA
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiScanStateChange**.|
| callback | Callback&lt;number&gt; | Yes| Callback invoked to return the WLAN scan state.|
**WLAN scan states**
| **Value**| **Description**|
| -------- | -------- |
| 0 | Scan failed.|
| 1 | Scan successful.|
## wifi.off('wifiScanStateChange')<sup>9+</sup>
off(type: "wifiScanStateChange", callback?: Callback&lt;number&gt;): void
Unregisters the WLAN scan state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.STA
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiScanStateChange**.|
| callback | Callback&lt;number&gt; | No| Callback for the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('wifiRssiChange')<sup>9+</sup>
on(type: "wifiRssiChange", callback: Callback&lt;number&gt;): void
Registers the RSSI change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.STA
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiRssiChange**.|
| callback | Callback&lt;number&gt; | Yes| Callback invoked to return the RSSI, in dBm.|
## wifi.off('wifiRssiChange')<sup>9+</sup>
off(type: "wifiRssiChange", callback?: Callback&lt;number&gt;): void
Unregisters the RSSI change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.STA
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiRssiChange**.|
| callback | Callback&lt;number&gt; | No| Callback for the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('hotspotStateChange')<sup>9+</sup>
on(type: "hotspotStateChange", callback: Callback&lt;number&gt;): void
Registers the hotspot state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.AP.Core
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **hotspotStateChange**.|
| callback | Callback&lt;number&gt; | Yes| Callback invoked to return the hotspot state.|
**Hotspot states**
| **Value**| **Description**|
| -------- | -------- |
| 0 | Deactivated|
| 1 | Activated|
| 2 | Activating|
| 3 | Deactivating|
## wifi.off('hotspotStateChange')<sup>9+</sup>
off(type: "hotspotStateChange", callback?: Callback&lt;number&gt;): void
Unregisters the hotspot state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.AP.Core
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **hotspotStateChange**.|
| callback | Callback&lt;number&gt; | No| Callback for the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('p2pStateChange')<sup>9+</sup>
on(type: "p2pStateChange", callback: Callback&lt;number&gt;): void
Registers the P2P state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pStateChange**.|
| callback | Callback&lt;number&gt; | Yes| Callback invoked to return the P2P state.|
**P2P states**
| **Value**| **Description**|
| -------- | -------- |
| 1 | Available|
| 2 | Opening|
| 3 | Opened|
| 4 | Closing|
| 5 | Closed|
## wifi.off('p2pStateChange')<sup>9+</sup>
off(type: "p2pStateChange", callback?: Callback&lt;number&gt;): void
Unregisters the P2P state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pStateChange**.|
| callback | Callback&lt;number&gt; | No| Callback for the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('p2pConnectionChange')<sup>9+</sup>
on(type: "p2pConnectionChange", callback: Callback&lt;WifiP2pLinkedInfo&gt;): void
Registers the P2P connection state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pConnectionChange**.|
| callback | Callback&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo9)&gt; | Yes| Callback invoked to return the P2P connection state.|
## wifi.off('p2pConnectionChange')<sup>9+</sup>
off(type: "p2pConnectionChange", callback?: Callback&lt;WifiP2pLinkedInfo&gt;): void
Unregisters the P2P connection state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pConnectionChange**.|
| callback | Callback&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo9)&gt; | No| Callback for the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('p2pDeviceChange')<sup>9+</sup>
on(type: "p2pDeviceChange", callback: Callback&lt;WifiP2pDevice&gt;): void
Registers the P2P device state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pDeviceChange**.|
| callback | Callback&lt;[WifiP2pDevice](#wifip2pdevice9)&gt; | Yes| Callback invoked to return the P2P device state.|
## wifi.off('p2pDeviceChange')<sup>9+</sup>
off(type: "p2pDeviceChange", callback?: Callback&lt;WifiP2pDevice&gt;): void
Unregisters the P2P device state change events.
**Required permissions**: ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pDeviceChange**.|
| callback | Callback&lt;[WifiP2pDevice](#wifip2pdevice9)&gt; | No| Callback for the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('p2pPeerDeviceChange')<sup>9+</sup>
on(type: "p2pPeerDeviceChange", callback: Callback&lt;WifiP2pDevice[]&gt;): void
Registers the P2P peer device state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.|
| callback | Callback&lt;[WifiP2pDevice[]](#wifip2pdevice9)&gt; | Yes| Callback invoked to return the P2P peer device state.|
## wifi.off('p2pPeerDeviceChange')<sup>9+</sup>
off(type: "p2pPeerDeviceChange", callback?: Callback&lt;WifiP2pDevice[]&gt;): void
Unregisters the P2P peer device state change events.
**Required permissions**: ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.|
| callback | Callback&lt;[WifiP2pDevice[]](#wifip2pdevice9)&gt; | No| Callback for the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('p2pPersistentGroupChange')<sup>9+</sup>
on(type: "p2pPersistentGroupChange", callback: Callback&lt;void&gt;): void
Registers the P2P persistent group state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.|
| callback | Callback&lt;void&gt; | Yes| Callback invoked to return the P2P persistent group state.|
## wifi.off('p2pPersistentGroupChange')<sup>9+</sup>
off(type: "p2pPersistentGroupChange", callback?: Callback&lt;void&gt;): void
Unregisters the P2P persistent group state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.|
| callback | Callback&lt;void&gt; | No| Callback for the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('p2pDiscoveryChange')<sup>9+</sup>
on(type: "p2pDiscoveryChange", callback: Callback&lt;number&gt;): void
Registers the P2P device discovery state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pDiscoveryChange**.|
| callback | Callback&lt;number&gt; | Yes| Callback invoked to return the P2P device discovery state.|
**P2P discovered device states**
| **Value**| **Description**|
| -------- | -------- |
| 0 | Initial state.|
| 1 | Discovered.|
## wifi.off('p2pDiscoveryChange')<sup>9+</sup>
off(type: "p2pDiscoveryChange", callback?: Callback&lt;number&gt;): void
Unregisters the P2P device discovery state change events.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.P2P
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pDiscoveryChange**.|
| callback | Callback&lt;number&gt; | No| Callback for the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
# WLAN Extension Interface
This **wifiext** module provides WLAN extension interfaces for non-universal products.
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
The APIs described in this document are used only for non-universal products, such as routers.
## Modules to Import
```js
import wifiManagerExt from '@ohos.wifiManagerExt';
```
## wifiext.enableHotspot
enableHotspot(): boolean;
Enables the WLAN hotspot.
**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT
**System capability**: SystemCapability.Communication.WiFi.AP.Extension
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifiext.disableHotspot
disableHotspot(): boolean;
Disables the WLAN hotspot.
**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT
**System capability**: SystemCapability.Communication.WiFi.AP.Extension
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifiext.getSupportedPowerModel
getSupportedPowerModel(): Promise&lt;Array&lt;PowerModel&gt;&gt;
Obtains the supported power models. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.AP.Extension
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;Array&lt;[PowerModel](#powermodel)&gt;&gt; | Promise used to return the power models obtained.|
## PowerModel
Enumerates the power models.
**System capability**: SystemCapability.Communication.WiFi.AP.Extension
| Name| Value| Description|
| -------- | -------- | -------- |
| SLEEPING | 0 | Sleeping|
| GENERAL | 1 | General|
| THROUGH_WALL | 2 | Through_wall|
## wifiext.getSupportedPowerModel
getSupportedPowerModel(callback: AsyncCallback&lt;Array&lt;PowerModel&gt;&gt;): void
Obtains the supported power models. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.AP.Extension
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;Array&lt;[PowerModel](#powermodel)&gt;&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.|
## wifiext.getPowerModel
getPowerModel(): Promise&lt;PowerModel&gt;
Obtains the power model. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.AP.Extension
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[PowerModel](#powermodel)&gt; | Promise used to return the power model obtained.|
## wifiext.getPowerModel
getPowerModel(callback: AsyncCallback&lt;PowerModel&gt;): void
Obtains the power model. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.AP.Extension
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[PowerModel](#powermodel)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power model obtained. If **err** is not **0**, an error has occurred.|
## wifiext.setPowerModel
setPowerModel(model: PowerModel) : boolean;
Sets the power model.
**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT
**System capability**: SystemCapability.Communication.WiFi.AP.Extension
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| model | [PowerModel](#powermodel) | Yes| Power model to set.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
# WLAN # @ohos.wifiext
This **wifiext** module provides WLAN extension interfaces for non-universal products. This **wifiext** module provides WLAN extension interfaces for non-universal products.
> **NOTE**<br> > **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
The APIs described in this document are used only for non-universal products, such as routers. The APIs described in this document are used only for non-universal products, such as routers.
...@@ -69,7 +71,7 @@ Enumerates the power models. ...@@ -69,7 +71,7 @@ Enumerates the power models.
**System capability**: SystemCapability.Communication.WiFi.AP.Extension **System capability**: SystemCapability.Communication.WiFi.AP.Extension
| Name| Default Value| Description| | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| SLEEPING | 0 | Sleeping| | SLEEPING | 0 | Sleeping|
| GENERAL | 1 | General| | GENERAL | 1 | General|
...@@ -90,7 +92,7 @@ Obtains the supported power models. This API uses an asynchronous callback to re ...@@ -90,7 +92,7 @@ Obtains the supported power models. This API uses an asynchronous callback to re
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[PowerModel](#powermodel)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| | callback | AsyncCallback&lt;Array&lt;[PowerModel](#powermodel)&gt;&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.|
## wifiext.getPowerModel ## wifiext.getPowerModel
...@@ -141,7 +143,7 @@ setPowerModel(model: PowerModel) : boolean; ...@@ -141,7 +143,7 @@ setPowerModel(model: PowerModel) : boolean;
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| model | AsyncCallback&lt;[PowerModel](#powermodel)&gt; | Yes| Power model to set.| | model | [PowerModel](#powermodel) | Yes| Power model to set.|
**Return value** **Return value**
......
# NFC Error Codes
## 3100101
**Error Message**
NFC opening or closing state is abnormal in service.
**Description**
The NFC service fails to enable or disable NFC.
**Possible Causes**
Communication with the NFC service failed.
**Solution**
Enable or disable NFC again.
## 3100201
**Error Message**
Tag running state is abnormal in service.
**Description**
An error occurs when the NFC service executes the tag service logic.
**Possible Causes**
1. The tag parameters do not match the API to invoke.
2. The NFC is disabled.
3. The tag is disconnected before the tag operation.
4. The tag chip returns an error status or response timeout.
5. Binding with the NFC service has not been established.
**Solution**
1. Check whether the NFC parameters match the API to invoke.
2. Enable NFC for the device.
3. Connect to the tag and then perform the read and write operations.
4. Touch and read the card again.
5. Exit the app and read the card again.
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册