基于安卓
import NfcAdapter from 'android.nfc.NfcAdapter';
import Tag from "android.nfc.Tag"
import Ndef from "android.nfc.tech.Ndef";
let nfcAdapter : NfcAdapter | null = null;
let callbacks : ((data: string) => void) | null = null;
/**
这里会提示 类型“ReaderCallback”不是构造函数类型。
不用管
*/
class temps extends NfcAdapter.ReaderCallback {
constructor() {
super()
}
/**
这里会提示 此成员不能有 "override" 修饰符,因为它的包含类 "temps" 不扩展其他类。
不用管
*/
override onTagDiscovered(tag : Tag) {
const byteArray = tag!.getId();
const result = (byteArray[0] & 0xFF) << 24 |
(byteArray[1] & 0xFF) << 16 |
(byteArray[2] & 0xFF) << 8 |
(byteArray[3] & 0xFF);
// 调用返回值
(callbacks as (data: string) => void)(result.toString())
setTimeout(() => { // 用于解决低版本安卓 enableReaderMode 无法重复启动问题
disableNFCReaderMode();
}, 1000)
}
}
export function disableNFCReaderMode() {
// 禁用NFC读取器模式
if(nfcAdapter !== null) {
console.log("关闭NFC读取器模式");
(nfcAdapter as NfcAdapter)!.disableReaderMode(UTSAndroid.getUniActivity());
nfcAdapter = null;
}
if(callbacks !== null) {
callbacks = null;
}
}
export function readNFC(callback: (data: string) => void) {
const context = UTSAndroid.getAppContext();
nfcAdapter = NfcAdapter.getDefaultAdapter(context);
try{
callbacks = callback;
(nfcAdapter as NfcAdapter)!.enableReaderMode(UTSAndroid.getUniActivity()!, new temps(), (
NfcAdapter.FLAG_READER_NFC_A |
NfcAdapter.FLAG_READER_NFC_B |
NfcAdapter.FLAG_READER_NFC_F |
NfcAdapter.FLAG_READER_NFC_V |
NfcAdapter.FLAG_READER_NFC_BARCODE
), null)
uni.showToast({
title: "启动NFC读取器模式",
icon: "none"
})
}catch(e){
uni.showToast({
title: "NFC启动失败",
icon: "error"
})
}
}