Near Field Communication (NFC) is a high-frequency radio technology that enables communication between devices over a distance less than 10 cm. NFC operates at 13.56 MHz. With NFC technologies, electronic devices can read data from tags or write data to tags.
NFC tags support one or more communications technologies listed as follows:
An electronic device touches an NFC tag via the NFC antenna to read or write the NFC tag data. NFC tags can be read and written by a started application (foreground mode) on a device or without starting an application (background mode).
Reading or writing an NFC tag by a started application
An application started on a device reads or writes the NFC tag. That is, the user starts the application to read and write the NFC tag. The user starts the application, opens the application page, and taps the device on the NFC tag. In this case, the retrieved tag data can be distributed only to the foreground application.
Reading or writing an NFC tag without starting an application
The user taps the device on an NFC tag without starting any application. Then, the device selects an application based on the type of the NFC tag technology. If multiple applications are matched, an application selector will be displayed, listing all the available applications for the user to choose from. After the user selects an application, the NFC tag read/write page of the application is automatically displayed.
Reading or writing an NDEF tag to implement common features
NFC on phones supports reading card information and redirecting users to ecosystem apps. Two methods are available: using the general-purpose NDEF protocol or integrating with the AirTouch service.
For more information about the NDEF tag format specifications, see the NFC Forum.
Constraints
No matter whether the foreground mode or background mode is used, the NFC tag can be discovered by the device only when the device screen is unlocked and illuminated.
For details about the JS APIs and sample code for NFC tag read/write, see @ohos.nfc.tag (Standard NFC Tags).
The following table describes the APIs for obtaining objects of the tags that use different NFC tag technologies. The objects obtained are used to read and write NFC tags.
| Name | Supported Since | Function Description |
|---|---|---|
| getNfcA(tagInfo: TagInfo): NfcATag | API version 9 | Obtains the tag object of the NfcA technology type. |
| getNfcB(tagInfo: TagInfo): NfcBTag | API version 9 | Obtains the tag object of the NfcB technology type. |
| getNfcF(tagInfo: TagInfo): NfcFTag | API version 9 | Obtains the tag object of the NfcF technology type. |
| getNfcV(tagInfo: TagInfo): NfcVTag | API version 9 | Obtains the tag object of the NfcV technology type. |
| getIsoDep(tagInfo: TagInfo): IsoDepTag | API version 9 | Obtains the tag object of the IsoDep technology type. |
| getNdef(tagInfo: TagInfo): NdefTag | API version 9 | Obtains the tag object of the NDEF technology type. |
| getMifareClassic(tagInfo: TagInfo): MifareClassicTag | API version 9 | Obtains the tag object of the MIFARE Classic technology type. |
| getMifareUltralight(tagInfo: TagInfo): MifareUltralightTag | API version 9 | Obtains the tag object of the MifareUltralight technology type. |
Based on service requirements, you can implement foreground card reading, background card reading, or jump to the corresponding application through a customized tag. The three card reading methods differ in code implementation and tag content.
Reading or writing an NFC tag by a started application
Reading or writing an NFC tag without starting an application
NDEF format tag customization
There are requirements on the content of NFC tags. An NDEF tag may contain one or more records, in which application-related information (package name/URI/AirtouchId) must be written. This enables the application to be launched with a single tap when it is running in the background.
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ts",
"description": "$string:EntryAbility_desc",
"icon": "$media:icon",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:icon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"ohos.want.action.home",
// The actions field must contain ohos.nfc.tag.action.TAG_FOUND.
"ohos.nfc.tag.action.TAG_FOUND"
]
}
]
}
],
"requestPermissions": [
{
// Add the NFC tag operation permission.
"name": "ohos.permission.NFC_TAG",
"reason": "$string:app_name",
}
] import { tag, nfcController } from '@kit.ConnectivityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { AbilityConstant, UIAbility, Want, bundleManager } from '@kit.AbilityKit';
let nfcTagElementName: bundleManager.ElementName;
let foregroundRegister: boolean;
async function readerModeCb(error: BusinessError, tagInfo: tag.TagInfo) {
if (!error) {
// Obtain an NFC tag object of the specific technology type.
if (tagInfo == null) {
hilog.error(0x0000, 'testTag', 'readerModeCb tagInfo is invalid');
return;
}
if (tagInfo.uid == null) {
hilog.error(0x0000, 'testTag', 'readerModeCb uid is invalid');
return;
}
if (tagInfo.technology == null || tagInfo.technology.length == 0) {
hilog.error(0x0000, 'testTag', 'readerModeCb technology is invalid');
return;
}
// The NFC tag may support multiple technology types. Select a specific technology type to read or write tag data.
// The following sample code is based on the IsoDep technology.
let isoDep: tag.IsoDepTag | null = null;
for (let i = 0; i < tagInfo.technology.length; i++) {
if (tagInfo.technology[i] == tag.ISO_DEP) {
try {
isoDep = tag.getIsoDep(tagInfo);
} catch (error) {
hilog.error(0x0000, 'testTag', 'readerModeCb getIsoDep error = %{public}s', JSON.stringify(error));
return;
}
}
// You can also use other technology types as required.
}
if (isoDep == null) {
hilog.error(0x0000, 'testTag', 'readerModeCb getIsoDep is invalid');
return;
}
// Connect to the NFC tag via IsoDep.
try {
isoDep.connect();
} catch (error) {
hilog.error(0x0000, 'testTag', 'readerModeCb isoDep.connect() error = %{public}s', JSON.stringify(error));
return;
}
if (!isoDep.isConnected()) {
hilog.error(0x0000, 'testTag', 'readerModeCb isoDep.isConnected() false.');
return;
}
// Send a command to the connected NFC tag to obtain the response data.
let cmdData = [0x01, 0x02, 0x03, 0x04]; // Modify the command data as required.
try {
isoDep.transmit(cmdData).then((response: number[]) => {
hilog.info(0x0000, 'testTag', 'readerModeCb isoDep.transmit() response = %{public}s.', JSON.stringify(response));
}).catch((err: BusinessError) => {
hilog.error(0x0000, 'testTag', 'readerModeCb isoDep.transmit() err = %{public}s.', JSON.stringify(err));
return;
});
} catch (businessError) {
hilog.error(0x0000, 'testTag', 'readerModeCb isoDep.transmit() businessError = %{public}s.', JSON.stringify(businessError));
return;
}
} else {
hilog.info(0x0000, 'testTag', 'readerModeCb readerModeCb error %{public}s', JSON.stringify(error));
}
}
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
// Check whether the device supports the NFC feature.
if (!canIUse("SystemCapability.Communication.NFC.Core")) {
hilog.error(0x0000, 'testTag', 'NFC System Capability not supported.');
return;
}
if (!nfcController.isNfcSupported()) {
hilog.error(0x0000, 'testTag', 'NFC not supported on this device.');
return;
}
// Initialize element names of the NFC tag based on the application information.
nfcTagElementName = {
bundleName: want.bundleName ?? '',
abilityName: want.abilityName ?? '',
moduleName: want.moduleName,
}
}
onForeground() {
// Switch the application to the foreground and call the foreground dispatch API to enable the foreground application to preferentially process the discovered NFC tag.
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
if (nfcTagElementName != undefined) {
// Select an appropriate technology type based on service requirements.
let techList: number[] = [tag.NFC_A, tag.NFC_B, tag.NFC_F, tag.NFC_V];
try {
tag.on('readerMode', nfcTagElementName, techList, readerModeCb);
foregroundRegister = true;
} catch (error) {
hilog.error(0x0000, 'testTag', 'on readerMode error = %{public}s', JSON.stringify(error));
}
}
}
onBackground() {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
// When exiting the NFC tag page, call the tag.off API to exit the foreground dispatch mode.
if (foregroundRegister) {
foregroundRegister = false;
try {
tag.off('readerMode', nfcTagElementName);
} catch (error) {
hilog.error(0x0000, 'testTag', 'off readerMode error = %{public}s', JSON.stringify(error));
}
}
}
} To enable NFC tags to be read without starting an application, declare NFC-related attributes in the module.json5 file.
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ts",
"description": "$string:EntryAbility_desc",
"icon": "$media:icon",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:icon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"ohos.want.action.home",
// The actions field must contain ohos.nfc.tag.action.TAG_FOUND.
"ohos.nfc.tag.action.TAG_FOUND"
],
// You must define at least one technology type based on service requirements. **tag-tech/** is the prefix, followed by the technology type description.
"uris": [
{
"type":"tag-tech/NfcA"
},
{
"type":"tag-tech/IsoDep"
}
// Add other technology types if necessary.
// Example: NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable
]
}
]
}
],
"requestPermissions": [
{
// Add the NFC tag operation permission.
"name": "ohos.permission.NFC_TAG",
"reason": "$string:app_name",
}
] import { tag } from '@kit.ConnectivityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
// Obtain an NFC tag object of the specific technology type.
let tagInfo: tag.TagInfo;
try {
tagInfo = tag.getTagInfo(want);
} catch (error) {
hilog.error(0x0000, 'testTag', 'getTagInfo error = %{public}s', JSON.stringify(error));
return;
}
if (tagInfo == null) {
hilog.error(0x0000, 'testTag', 'tagInfo is invalid');
return;
}
if (tagInfo.uid == null) {
hilog.error(0x0000, 'testTag', 'uid is invalid');
return;
}
if (tagInfo.technology == null || tagInfo.technology.length == 0) {
hilog.error(0x0000, 'testTag', 'technology is invalid');
return;
}
// The NFC tag may support multiple technology types. Select a specific technology type to read or write tag data.
// The following sample code is based on the IsoDep technology.
let isoDep: tag.IsoDepTag | null = null;
for (let i = 0; i < tagInfo.technology.length; i++) {
if (tagInfo.technology[i] == tag.ISO_DEP) {
try {
isoDep = tag.getIsoDep(tagInfo);
} catch (error) {
hilog.error(0x0000, 'testTag', 'getIsoDep error = %{public}s', JSON.stringify(error));
return;
}
}
// You can also use other technology types as required.
}
if (isoDep == null) {
hilog.error(0x0000, 'testTag', 'getIsoDep is invalid');
return;
}
// Connect to the NFC tag via IsoDep.
try {
isoDep.connect();
} catch (error) {
hilog.error(0x0000, 'testTag', 'isoDep.connect() error = %{public}s', JSON.stringify(error));
return;
}
if (!isoDep.isConnected()) {
hilog.error(0x0000, 'testTag', 'isoDep.isConnected() false.');
return;
}
// Send a command to the connected NFC tag to obtain the response data.
let cmdData = [0x01, 0x02, 0x03, 0x04]; // Modify the command data as required.
try {
isoDep.transmit(cmdData).then((response: number[]) => {
hilog.info(0x0000, 'testTag', 'isoDep.transmit() response = %{public}s.', JSON.stringify(response));
}).catch((err: BusinessError) => {
hilog.error(0x0000, 'testTag', 'isoDep.transmit() err = %{public}s.', JSON.stringify(err));
return;
});
} catch (businessError) {
hilog.error(0x0000, 'testTag', 'isoDep.transmit() businessError = %{public}s.', JSON.stringify(businessError));
return;
}
}
} NFC tag customization
If URI data is required when the application is launched, the first Record must be of the URI type.
Example of receiving parameters in an application
When the application is launched, it can complete its service logic through the parameters passed in want. When the application is launched through a card, the want content carried is as follows:
want = {
"deviceId": "",
"bundleName": "xxx",
"abilityName": "xxx",
"moduleName": "xxx",
"uri": "https://xxx.com", // URI written into the NFC card.
"type": "",
"flags": 0,
"action": "action.system.home",
"parameters": {
// NFC-related fields.
"Atqa": "4400",
"MifareUltralightC": false,
"NdefForumType": 2,
"NdefMsg": "xxxxxxxxxx", // Complete NDEF message in hexadecimal bytecode format.
"NdefTagLength": 868,
"NdefTagMode": 2,
"Sak": 0,
"tagRfDiscId": 2,
"technology": [1, 9, 6], // Protocol types supported by the read card, such as NfcA, NfcB, NfcF, NfcV, Ndef, and IsoDep.
"uid": "xxxxxxxx", // UID of the read card.
// Other content.
"component.startup.newRules": true,
"isCallBySCB": false,
"isShellCall": false,
"moduleName": "entry",
"ohos.aafwk.param.callerAbilityName": "",
"ohos.aafwk.param.callerBundleName": "",
"ohos.aafwk.param.callerNativeName": "_nfc_service", // NFC process name.
"ohos.aafwk.param.callerPid": xxx,
"ohos.aafwk.param.callerToken": xxxx,
"ohos.aafwk.param.callerUid": xxxx,
"ohos.aafwk.param.displayId": 0,
"ohos.dlp.params.sandbox": false,
"ohos.param.callerAppCloneIndex": 0,
"remoteTagService": {
"type": "RemoteObject",
"value": {}
}
},
"fds": {},
"entities": ["entity.system.home"]
} NFC tag assistant and NFC tag tools.
Write an NDEF record containing the redirection information of the target app to the NFC tag. After the device taps the tag, the system parses the NDEF record and redirects to the corresponding app. For the tag format and card writing method, see NDEF Format Tag Customization.