HarmonyOS 鸿蒙Next NFC读取的demo

HarmonyOS 鸿蒙Next NFC读取的demo

麻烦提供一个NFC读取的demo

3 回复

更多关于HarmonyOS 鸿蒙Next NFC读取的demo的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


HarmonyOS 鸿蒙Next NFC读取的Demo通常涉及以下几个关键步骤和组件:

  1. 权限声明: 在config.json文件中声明NFC读取权限,确保应用有权限访问NFC硬件。

  2. NFC适配器初始化: 使用NfcManager获取NFC适配器,并进行初始化。这通常包括检查NFC硬件是否可用、注册NFC事件监听器等。

  3. NFC卡片扫描: 通过NFC适配器启动卡片扫描,并处理扫描到的NFC标签。这通常涉及到解析NFC标签中的数据,例如NDEF消息。

  4. 数据处理: 根据NFC标签中的数据类型进行相应的处理。例如,如果标签包含URL,应用可以打开该URL;如果包含文本信息,应用可以显示该文本。

  5. UI展示: 在应用的UI中展示NFC读取的结果。这可能需要更新TextView、ImageView等UI组件。

  6. 错误处理: 处理NFC读取过程中可能出现的错误,例如NFC硬件不可用、标签读取失败等。

以下是一个简化的示例代码框架:

// 伪代码示例,实际代码需根据HarmonyOS SDK文档编写
let nfcManager = getNfcManager();
nfcManager.initNfcAdapter((adapter) => {
    adapter.startNfcDiscovery((tag) => {
        // 处理NFC标签数据
    }, (error) => {
        // 处理错误
    });
});

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

HarmonyOS 鸿蒙Next NFC前台读取Demo

  1. 在module.json5文件中声明NFC标签读取的权限,以及声明NFC标签特定的action。
  2. import需要的tag模块和其他相关的模块。
  3. 判断设备是否支持NFC能力。
  4. 调用tag模块中前台优先的接口,使能前台应用程序优先处理所发现的NFC标签功能。
  5. 获取特定技术类型的NFC标签对象。
  6. 执行读写接口完成标签数据的读取或写入数据到标签。 退出应用程序NFC标签页面时,调用tag模块退出前台优先功能。
    "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": [
              "action.system.home",

              // Add the nfc tag action to filter out for this application.
              "ohos.nfc.tag.action.TAG_FOUND"
            ]
          }
        ]
      }
    ],
    "requestPermissions": [
      {
        // Add the permission for nfc tag operations.
        "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, bundleManager } from '@kit.AbilityKit';

let nfcTagElementName: bundleManager.ElementName;
let foregroundRegister: boolean;

async function readerModeCb(error : BusinessError, tagInfo : tag.TagInfo) {
  if (!error) {
    // 获取特定技术类型的NFC标签对象
    if (tagInfo == null || tagInfo == undefined) {
      hilog.error(0x0000, 'testTag', 'readerModeCb tagInfo is invalid');
      return;
    }
    if (tagInfo.uid == null || tagInfo.uid == undefined) {
      hilog.error(0x0000, 'testTag', 'readerModeCb uid is invalid');
      return;
    }
    if (tagInfo.technology == null || tagInfo.technology == undefined || tagInfo.technology.length == 0) {
      hilog.error(0x0000, 'testTag', 'readerModeCb technology is invalid');
      return;
    }

    // 执行读写接口完成标签数据的读取或写入数据到标签
    // use the IsoDep technology to access this nfc tag.
    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;
        }
      }
      // use other technology to access this nfc tag if necessary.
    }
    if (isoDep == undefined) {
      hilog.error(0x0000, 'testTag', 'readerModeCb getIsoDep is invalid');
      return;
    }

    // connect to this nfc tag using IsoDep technology.
    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;
    }

    // transmit data to the connected tag.
    let cmdData = [0x01, 0x02, 0x03, 0x04]; // please change the raw data to be correct.
    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');

    // 判断设备是否支持NFC能力
    if (!canIUse("SystemCapability.Communication.NFC.Core")) {
      hilog.error(0x0000, 'testTag', 'nfc unavailable.');
      return;
    }

    nfcTagElementName = {
      bundleName: want.bundleName ?? '',
      abilityName: want.abilityName ?? '',
      moduleName: want.moduleName,
    }
  }

  onForeground() {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
    if (nfcTagElementName != undefined) {
      // 调用tag模块中前台优先的接口,使能前台应用程序优先处理所发现的NFC标签功能
      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() {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
    // 退出应用程序NFC标签页面时,调用tag模块退出前台优先功能
    if (foregroundRegister) {
      foregroundRegister = false;
      try {
        tag.off('readerMode', nfcTagElementName);
      } catch (error) {
        hilog.error(0x0000, 'testTag', 'off readerMode error = %{public}s', JSON.stringify(error));
      }
    }
  }
}

HarmonyOS 鸿蒙Next后台读取demo

  1. 在module.json5文件中声明NFC标签读取的权限,声明NFC标签特定的action,以及声明本应用程序的能够处理的NFC标签技术类型。
  2. import需要的tag模块和其他相关的模块。
  3. 获取特定技术类型的NFC标签对象。 执行读写接口完成标签数据的读取或写入数据到标签。
    "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": [
              "action.system.home",

              // Add the nfc tag action to filter out for this application.
              "ohos.nfc.tag.action.TAG_FOUND"
            ],
            "uris": [
              {
                  "type":"tag-tech/NfcA"
              },
              {
                  "type":"tag-tech/IsoDep"
              }
              // Add other technologies if necessary,
              // such as: NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable
            ]
          }
        ]
      }
    ],
    "requestPermissions": [
      {
        // Add the permission for nfc tag operations.
        "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');

    // 获取特定技术类型的NFC标签对象
    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 || tagInfo == undefined) {
      hilog.error(0x0000, 'testTag', 'tagInfo is invalid');
      return;
    }
    if (tagInfo.uid == null || tagInfo.uid == undefined) {
      hilog.error(0x0000, 'testTag', 'uid is invalid');
      return;
    }
    if (tagInfo.technology == null || tagInfo.technology == undefined || tagInfo.technology.length == 0) {
      hilog.error(0x0000, 'testTag', 'technology is invalid');
      return;
    }

    // 执行读写接口完成标签数据的读取或写入数据到标签
    // use the IsoDep technology to access this nfc tag.
    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;
        }
      }
      // use other technology to access this nfc tag if necessary.
    }
    if (isoDep == undefined) {
      hilog.error(0x0000, 'testTag', 'getIsoDep is invalid');
      return;
    }

    // connect to this nfc tag using IsoDep technology.
    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;
    }

    // transmit data to the connected tag.
    let cmdData = [0x01, 0x02, 0x03, 0x04]; // please change the raw data to be correct.
    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;
    }
  }
}
回到顶部