HarmonyOS 如何实现通过NFC实现手机给卡充值的功能?

需要的能力是使用NFC适配器建立连接,发送数据和接收数据,对应的业务场景就是使用NFC天线对公交进行充值,NFC读写CPU卡的部分,ISO-14443-4协议规范

阅读 687
1 个回答

标准NFC-Tag tag.TagInfo demo:

import tag from '@ohos.nfc.tag';
import UIAbility from '@ohos.app.ability.UIAbility';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import Want from '@ohos.app.ability.Want'

export default class EntryAbility extends UIAbility {
  onCreate(want : Want, launchParam: AbilityConstant.LaunchParam) {
    // add other code here...

    // want is initialized by nfc service, contains tag info for this found tag
    let tagInfo : tag.TagInfo | null = null;
    try {
      tagInfo = tag.getTagInfo(want);
    } catch (error) {
      console.error("tag.getTagInfo catched error: " + error);
    }
    if (tagInfo == null || tagInfo == undefined) {
      console.log("no TagInfo to be created, ignore it.");
      return;
    }

    // get the supported technologies for this found tag.
    let isNfcATag = false;
    let isIsoDepTag = false;
    for (let i = 0; i < tagInfo.technology.length; i++) {
      if (tagInfo.technology[i] == tag.NFC_A) {
        isNfcATag = true;
      }

      if (tagInfo.technology[i] == tag.ISO_DEP) {
        isIsoDepTag = true;
      }
      // also check for technology: tag.NFC_B/NFC_F/NFC_V/NDEF/MIFARE_CLASSIC/MIFARE_ULTRALIGHT/NDEF_FORMATABLE
    }

    // use NfcA APIs to access the found tag.
    if (isNfcATag) {
      let nfcA : tag.NfcATag | null = null;
      try {
        nfcA = tag.getNfcATag(tagInfo);
      } catch (error) {
        console.error("tag.getNfcATag catched error: " + error);
      }
      // other code to read or write this found tag.
    }

    // use getIsoDep APIs to access the found tag.
    if (isIsoDepTag) {
      let isoDep : tag.IsoDepTag | null = null;
      try {
        isoDep = tag.getIsoDep(tagInfo);
      } catch (error) {
        console.error("tag.getIsoDep catched error: " + error);
      }
      // other code to read or write this found tag.
    }
    // use the same code to handle for "NfcA/NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable".
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题