目录

NFC Tag Read/Write Development

Introduction

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:

When to Use

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).

Available APIs

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.

Preparations

[h2]Choosing Between NFC Tag Foreground Read/Write, Background Read/Write, or Tag Customization

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.

  1. In the module.json5 configuration file, you do not need to statically declare the technology type of the target NFC tag. Instead, dynamically register the technology type by using tag.registerForegroundDispatch or tag.on.
  2. When dynamically registering foreground tag read/write via tag.registerForegroundDispatch or tag.on, you must specify the technology type of the NFC tags to be read in the input parameters.
  3. If you use tag.registerForegroundDispatch for registration, NFC card emulation can remain enabled and card interactions can be performed at the same time when the application is running in the foreground and enters the page. If you use tag.on for registration, NFC card emulation is disabled when the application is running in the foreground and enters the page, and card interactions cannot be performed at the same time.
  4. When the application page switches to the background, explicitly call tag.unregisterForegroundDispatch or tag.off to unregister and exit the foreground dispatch mode.
  1. In the module.json5 configuration file, statically declare the technology type of the target NFC tag. You must define at least one technology type based on service requirements. tag-tech/ is the prefix, followed by the technology type description.
  2. The technology type description is case-sensitive and must exactly match the actual technology type.
  • Application development since API version 9 supports the stage model, which is the mainstream and long-term evolution model.
  • All NFC tag read/write sample code is provided based on the stage model.

How to Develop

[h2]Accessing an NFC Tag by a Started Application

  1. Declare the permission required for NFC tag operations and the action for filtering the application in the module.json5 file.
  2. Import related modules.
  3. Check whether the device supports the NFC feature.
  4. Call the foreground-priority API of the tag module to enable the foreground app to preferentially process discovered NFC tags.
  5. Obtain an NFC tag object of the specific technology type.
  6. Read and write the tag data.
  7. Exit the foreground dispatch mode when the application exits the NFC tag page.
    "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));
      }
    }
  }
}

[h2]Accessing an NFC Tag Without Starting an Application

  1. In the module.json5 configuration file, declare the NFC tag operation permission, the NFC tag action, and the technology type.
  2. Import related modules.
  3. Obtain an NFC tag object of the specific technology type.
  4. Read and write the tag data.

To enable NFC tags to be read without starting an application, declare NFC-related attributes in the module.json5 file.

  1. The actions field must contain ohos.nfc.tag.action.TAG_FOUND and cannot be changed.
  2. The type field under uris must start with tag-tech/, followed by NfcA, NfcB, NfcF, NfcV, IsoDep, Ndef, MifareClassic, MifareUL, or NdefFormatable. If there are multiple types, enter each on a separate line. Incorrect settings will cause a parsing failure.
  3. The name field of requestPermissions is mandatory. It must be ohos.permission.NFC_TAG and cannot be changed.
  4. Wearable devices do not support reading NFC tags without starting an application.
    "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;
    }
  }
}

[h2]NDEF Format Tag Customization

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"]
    }

FAQs

[h2]What Are the Commonly Used Apps for Reading and Writing NFC Tags?

NFC tag assistant and NFC tag tools.

[h2]How to Implement App Redirection Through NFC Tap?

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.