文档管理中心
指南元服务开发指导基础能力开发基础通信NFCNFC标签读写开发指南

NFC标签读写开发指南

简介

近场通信(Near Field Communication,NFC)是一种短距高频的无线电技术,在13.56MHz频率运行,通信距离一般在10厘米距离内。电子设备可以通过NFC通信技术和NFC标签通信,从标签中读取数据,或写入数据到标签。

NFC标签可能会支持一种或多种通信技术,具体技术如下:

  • NfcA (也称为 ISO 14443-3A)

  • NfcB (也称为 ISO 14443-3B)

  • NfcF (也称为 JIS 6319-4)

  • NfcV (也称为 ISO 15693)

  • IsoDep

  • NDEF

  • MifareClassic

  • MifareUltralight

场景介绍

电子设备通过NFC天线位置触碰NFC标签卡片,完成NFC标签卡片的读取或写入。从使用场景上,可以分成NFC标签前台读写,和NFC标签后台读写。

  • NFC标签前台读写

    前台读写是指在触碰NFC标签之前,用户先在电子设备上打开特定的应用程序,用户明确想使用所打开的应用程序和NFC标签进行读写操作。用户打开应用程序在前台,并且进入应用的刷卡页面之后,电子设备触碰NFC标签,只会把读取到的卡片分发给前台应用。

  • NFC标签后台读写

    后台读写是指不打开特定的NFC标签应用程序,电子设备触碰发现NFC标签后,根据NFC标签的技术类型,分发给能够处理的应用程序。如果能匹配到多个应用程序,则弹出应用选择器列举出应用列表给用户手动选择。用户选择指定的应用后,自动跳转到应用程序的NFC标签读写卡页面。

  • 标签读写约束条件

    不管是前台读写,还是后台读写,电子设备能够发现NFC标签的前提条件是设备必须是亮屏和解锁状态。

接口说明

NFC标签读写完整的API说明以及示例代码请参考:NFC标签接口

获取不同技术类型标签对象的接口说明如下表,根据不同技术的标签对象来执行NFC标签的读写。

展开
接口名 功能描述
getNfcA(tagInfo: TagInfo): NfcATag 获取NfcA技术类型的标签对象。
getNfcB(tagInfo: TagInfo): NfcBTag 获取NfcB技术类型的标签对象。
getNfcF(tagInfo: TagInfo): NfcFTag 获取NfcF技术类型的标签对象。
getNfcV(tagInfo: TagInfo): NfcVTag 获取NfcV技术类型的标签对象。
getIsoDep(tagInfo: TagInfo): IsoDepTag 获取IsoDep技术类型的标签对象。
getNdef(tagInfo: TagInfo): NdefTag 获取NDEF技术类型的标签对象。
getMifareClassic(tagInfo: TagInfo): MifareClassicTag 获取MifareClassic技术类型的标签对象。
getMifareUltralight(tagInfo: TagInfo): MifareUltralightTag 获取MifareUltralight技术类型的标签对象。

开发步骤

前台读取标签

  1. 在module.json5文件中声明NFC标签读取的权限,以及声明NFC标签特定的action;

  2. import需要的tag模块和其他相关的模块;

  3. 判断设备是否支持NFC能力;

  4. 调用tag模块中前台优先的接口,使能前台应用程序优先处理所发现的NFC标签功能;

  5. 获取特定技术类型的NFC标签对象;

  6. 执行读写接口完成标签数据的读取或写入数据到标签;

  7. 退出应用程序NFC标签页面时,调用tag模块退出前台优先功能。

收起
自动换行
深色代码主题
复制
  1. "abilities": [
  2. {
  3. "name": "EntryAbility",
  4. "srcEntry": "./ets/entryability/EntryAbility.ts",
  5. "description": "$string:EntryAbility_desc",
  6. "icon": "$media:icon",
  7. "label": "$string:EntryAbility_label",
  8. "startWindowIcon": "$media:icon",
  9. "startWindowBackground": "$color:start_window_background",
  10. "exported": true,
  11. "skills": [
  12. {
  13. "entities": [
  14. "entity.system.home"
  15. ],
  16. "actions": [
  17. "action.system.home",
  18. // Add the nfc tag action to filter out for this application.
  19. "ohos.nfc.tag.action.TAG_FOUND"
  20. ]
  21. }
  22. ]
  23. }
  24. ],
  25. "requestPermissions": [
  26. {
  27. // Add the permission for nfc tag operations.
  28. "name": "ohos.permission.NFC_TAG",
  29. "reason": "$string:app_name",
  30. }
  31. ]
收起
自动换行
深色代码主题
复制
  1. import { tag } from '@kit.ConnectivityKit';
  2. import { BusinessError } from '@kit.BasicServicesKit';
  3. import { hilog } from '@kit.PerformanceAnalysisKit';
  4. import { AbilityConstant, UIAbility, Want, bundleManager } from '@kit.AbilityKit';
  5. let nfcTagElementName: bundleManager.ElementName;
  6. let foregroundRegister: boolean;
  7. async function readerModeCb(error : BusinessError, tagInfo : tag.TagInfo) {
  8. if (!error) {
  9. // 获取特定技术类型的NFC标签对象
  10. if (tagInfo == null || tagInfo == undefined) {
  11. hilog.error(0x0000, 'testTag', 'readerModeCb tagInfo is invalid');
  12. return;
  13. }
  14. if (tagInfo.uid == null || tagInfo.uid == undefined) {
  15. hilog.error(0x0000, 'testTag', 'readerModeCb uid is invalid');
  16. return;
  17. }
  18. if (tagInfo.technology == null || tagInfo.technology == undefined || tagInfo.technology.length == 0) {
  19. hilog.error(0x0000, 'testTag', 'readerModeCb technology is invalid');
  20. return;
  21. }
  22. // 执行读写接口完成标签数据的读取或写入数据到标签
  23. // use the IsoDep technology to access this nfc tag.
  24. let isoDep : tag.IsoDepTag | null = null;
  25. for (let i = 0; i < tagInfo.technology.length; i++) {
  26. if (tagInfo.technology[i] == tag.ISO_DEP) {
  27. try {
  28. isoDep = tag.getIsoDep(tagInfo);
  29. } catch (error) {
  30. hilog.error(0x0000, 'testTag', 'readerModeCb getIsoDep errCode: ' + (error as BusinessError).code + ', errMessage: ' + (error as BusinessError).message);
  31. return;
  32. }
  33. }
  34. // use other technology to access this nfc tag if necessary.
  35. }
  36. if (isoDep == undefined) {
  37. hilog.error(0x0000, 'testTag', 'readerModeCb getIsoDep is invalid');
  38. return;
  39. }
  40. // connect to this nfc tag using IsoDep technology.
  41. try {
  42. isoDep.connect();
  43. } catch (error) {
  44. hilog.error(0x0000, 'testTag', 'readerModeCb isoDep.connect errCode: ' + (error as BusinessError).code + ', errMessage: ' + (error as BusinessError).message);
  45. return;
  46. }
  47. if (!isoDep.isConnected()) {
  48. hilog.error(0x0000, 'testTag', 'readerModeCb isoDep.isConnected() false.');
  49. return;
  50. }
  51. // transmit data to the connected tag.
  52. let cmdData = [0x01, 0x02, 0x03, 0x04]; // please change the raw data to be correct.
  53. try {
  54. isoDep.transmit(cmdData).then((response : number[]) => {
  55. hilog.info(0x0000, 'testTag', 'readerModeCb isoDep.transmit() response = %{public}s.', JSON.stringify(response));
  56. }).catch((err : BusinessError)=> {
  57. hilog.error(0x0000, 'testTag', 'readerModeCb isoDep.transmit errCode: ' + err.code + ', errMessage: ' + err.message);
  58. return;
  59. });
  60. } catch (busiError) {
  61. hilog.error(0x0000, 'testTag', 'readerModeCb isoDep.transmit errCode: ' + (busiError as BusinessError).code + ', errMessage: ' + (busiError as BusinessError).message);
  62. return;
  63. }
  64. } else {
  65. hilog.info(0x0000, 'testTag', 'readerModeCb readerModeCb errCode: ' + error.code + ', errMessage: ' + error.message);
  66. }
  67. }
  68. export default class EntryAbility extends UIAbility {
  69. onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
  70. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
  71. // 判断设备是否支持NFC能力
  72. if (!canIUse("SystemCapability.Communication.NFC.Core")) {
  73. hilog.error(0x0000, 'testTag', 'nfc unavailable.');
  74. return;
  75. }
  76. nfcTagElementName = {
  77. bundleName: want.bundleName = '',
  78. abilityName: want.abilityName = '',
  79. moduleName: want.moduleName,
  80. }
  81. }
  82. onForeground() {
  83. // Ability has brought to foreground
  84. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  85. if (nfcTagElementName != undefined) {
  86. // 调用tag模块中前台优先的接口,使能前台应用程序优先处理所发现的NFC标签功能
  87. let techList : number[] = [tag.NFC_A, tag.NFC_B, tag.NFC_F, tag.NFC_V];
  88. try {
  89. tag.on('readerMode', nfcTagElementName, techList, readerModeCb);
  90. foregroundRegister = true;
  91. } catch (error) {
  92. hilog.error(0x0000, 'testTag', 'on readerMode errCode: ' + (error as BusinessError).code + ', errMessage: ' + (error as BusinessError).message);
  93. }
  94. }
  95. }
  96. onBackground() {
  97. // Ability has back to background
  98. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  99. // 退出应用程序NFC标签页面时,调用tag模块退出前台优先功能
  100. if (foregroundRegister) {
  101. foregroundRegister = false;
  102. try {
  103. tag.off('readerMode', nfcTagElementName);
  104. } catch (error) {
  105. hilog.error(0x0000, 'testTag', 'on readerMode errCode: ' + (error as BusinessError).code + ', errMessage: ' + (error as BusinessError).message);
  106. }
  107. }
  108. }
  109. }

后台读取标签

  1. 在module.json5文件中声明NFC标签读取的权限,声明NFC标签特定的action,以及声明本应用程序的能够处理的NFC标签技术类型;

  2. import需要的tag模块和其他相关的模块;

  3. 获取特定技术类型的NFC标签对象;

  4. 执行读写接口完成标签数据的读取或写入数据到标签。

收起
自动换行
深色代码主题
复制
  1. "abilities": [
  2. {
  3. "name": "EntryAbility",
  4. "srcEntry": "./ets/entryability/EntryAbility.ts",
  5. "description": "$string:EntryAbility_desc",
  6. "icon": "$media:icon",
  7. "label": "$string:EntryAbility_label",
  8. "startWindowIcon": "$media:icon",
  9. "startWindowBackground": "$color:start_window_background",
  10. "exported": true,
  11. "skills": [
  12. {
  13. "entities": [
  14. "entity.system.home"
  15. ],
  16. "actions": [
  17. "action.system.home",
  18. // Add the nfc tag action to filter out for this application.
  19. "ohos.nfc.tag.action.TAG_FOUND"
  20. ],
  21. "uris": [
  22. {
  23. "type":"tag-tech/NfcA"
  24. },
  25. {
  26. "type":"tag-tech/IsoDep"
  27. }
  28. // Add other technologies if necessary,
  29. // such as: NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable
  30. ]
  31. }
  32. ]
  33. }
  34. ],
  35. "requestPermissions": [
  36. {
  37. // Add the permission for nfc tag operations.
  38. "name": "ohos.permission.NFC_TAG",
  39. "reason": "$string:app_name",
  40. }
  41. ]
收起
自动换行
深色代码主题
复制
  1. import { tag } from '@kit.ConnectivityKit';
  2. import { BusinessError } from '@kit.BasicServicesKit';
  3. import { hilog } from '@kit.PerformanceAnalysisKit';
  4. import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
  5. export default class EntryAbility extends UIAbility {
  6. onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
  7. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
  8. // 获取特定技术类型的NFC标签对象
  9. let tagInfo : tag.TagInfo;
  10. try {
  11. tagInfo = tag.getTagInfo(want);
  12. } catch (error) {
  13. hilog.error(0x0000, 'testTag', 'getTagInfo errCode: ' + (error as BusinessError).code + ', errMessage: ' + (error as BusinessError).message);
  14. return;
  15. }
  16. if (tagInfo == null || tagInfo == undefined) {
  17. hilog.error(0x0000, 'testTag', 'tagInfo is invalid');
  18. return;
  19. }
  20. if (tagInfo.uid == null || tagInfo.uid == undefined) {
  21. hilog.error(0x0000, 'testTag', 'uid is invalid');
  22. return;
  23. }
  24. if (tagInfo.technology == null || tagInfo.technology == undefined || tagInfo.technology.length == 0) {
  25. hilog.error(0x0000, 'testTag', 'technology is invalid');
  26. return;
  27. }
  28. // 执行读写接口完成标签数据的读取或写入数据到标签
  29. // use the IsoDep technology to access this nfc tag.
  30. let isoDep : tag.IsoDepTag | null = null;
  31. for (let i = 0; i < tagInfo.technology.length; i++) {
  32. if (tagInfo.technology[i] == tag.ISO_DEP) {
  33. try {
  34. isoDep = tag.getIsoDep(tagInfo);
  35. } catch (error) {
  36. hilog.error(0x0000, 'testTag', 'getIsoDep errCode: ' + (error as BusinessError).code + ', errMessage: ' + (error as BusinessError).message);
  37. return;
  38. }
  39. }
  40. // use other technology to access this nfc tag if necessary.
  41. }
  42. if (isoDep == undefined) {
  43. hilog.error(0x0000, 'testTag', 'getIsoDep is invalid');
  44. return;
  45. }
  46. // connect to this nfc tag using IsoDep technology.
  47. try {
  48. isoDep.connect();
  49. } catch (error) {
  50. hilog.error(0x0000, 'testTag', 'isoDep.connect errCode: ' + (error as BusinessError).code + ', errMessage: ' + (error as BusinessError).message);
  51. return;
  52. }
  53. if (!isoDep.isConnected()) {
  54. hilog.error(0x0000, 'testTag', 'isoDep.isConnected() false.');
  55. return;
  56. }
  57. // transmit data to the connected tag.
  58. let cmdData = [0x01, 0x02, 0x03, 0x04]; // please change the raw data to be correct.
  59. try {
  60. isoDep.transmit(cmdData).then((response : number[]) => {
  61. hilog.info(0x0000, 'testTag', 'isoDep.transmit() response = %{public}s.', JSON.stringify(response));
  62. }).catch((err : BusinessError)=> {
  63. hilog.error(0x0000, 'testTag', 'isoDep.transmit errCode: ' + err.code + ', errMessage: ' + err.message);
  64. return;
  65. });
  66. } catch (busiError) {
  67. hilog.error(0x0000, 'testTag', 'isoDep.transmit errCode: ' + (busiError as BusinessError).code + ', errMessage: ' + (busiError as BusinessError).message);
  68. return;
  69. }
  70. }
  71. }
在 指南 中进行搜索
请输入您想要搜索的关键词