新建一个utils(随便起的)文件夹和pages同级
import store from '@/store/index.js'
// 包路径
const package_NdefRecord = 'android.nfc.NdefRecord';
const package_NdefMessage = 'android.nfc.NdefMessage';
const package_TECH_DISCOVERED = 'android.nfc.action.TECH_DISCOVERED';
const package_Intent = 'android.content.Intent';
const package_Activity = 'android.app.Activity';
const package_PendingIntent = 'android.app.PendingIntent';
const package_IntentFilter = 'android.content.IntentFilter';
const package_NfcAdapter = 'android.nfc.NfcAdapter';
const package_Ndef = 'android.nfc.tech.Ndef';
const package_NdefFormatable = 'android.nfc.tech.NdefFormatable';
const package_Parcelable = 'android.os.Parcelable';
const package_String = 'java.lang.String';
let NfcAdapter;
let NdefRecord;
let NdefMessage;
let readyWriteData = false; //开启写
let readyRead = true; //开启读
let noNFC = false;
let techListsArray = [
['android.nfc.tech.IsoDep'],
['android.nfc.tech.NfcA'],
['android.nfc.tech.NfcB'],
['android.nfc.tech.NfcF'],
['android.nfc.tech.Nfcf'],
['android.nfc.tech.NfcV'],
['android.nfc.tech.NdefFormatable'],
['android.nfc.tech.MifareClassi'],
['android.nfc.tech.MifareUltralight']
];
export default {
listenNFCStatus: function () {
// console.log("---------监听NFC状态--------------")
let that = this;
try {
let main = plus.android.runtimeMainActivity();
let Intent = plus.android.importClass('android.content.Intent');
let Activity = plus.android.importClass('android.app.Activity');
let PendingIntent = plus.android.importClass('android.app.PendingIntent');
let IntentFilter = plus.android.importClass('android.content.IntentFilter');
NfcAdapter = plus.android.importClass('android.nfc.NfcAdapter');
let nfcAdapter = NfcAdapter.getDefaultAdapter(main);
if (nfcAdapter == null) {
uni.showToast({
title: '设备不支持NFC!',
icon: 'none'
})
noNFC = true;
return;
}
if (!nfcAdapter.isEnabled()) {
uni.showToast({
title: '请在系统设置中先启用NFC功能!',
icon: 'none'
});
noNFC = true;
return;
} else {
noNFC = false;
}
let intent = new Intent(main, main.getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
let pendingIntent = PendingIntent.getActivity(main, 0, intent, 0);
let ndef = new IntentFilter("android.nfc.action.TECH_DISCOVERED");
ndef.addDataType("*/*");
let intentFiltersArray = [ndef];
plus.globalEvent.addEventListener('newintent', function () {
// console.log('newintent running');
// 轮询调用 NFC
setTimeout(that.nfcRuning(), 1000);
});
plus.globalEvent.addEventListener('pause', function (e) {
// console.log('pause running');
if (nfcAdapter) {
//关闭前台调度系统
//恢复默认状态
nfcAdapter.disableForegroundDispatch(main);
}
});
plus.globalEvent.addEventListener('resume', function (e) {
// console.log('resume running');
if (nfcAdapter) {
//开启前台调度系统
// 优于所有其他NFC
nfcAdapter.enableForegroundDispatch(main, pendingIntent, intentFiltersArray,
techListsArray);
}
});
nfcAdapter.enableForegroundDispatch(main, pendingIntent, intentFiltersArray, techListsArray);
} catch (e) {
console.error(e);
}
},
nfcRuning: function () { //
// console.log("--------------NFC 运行---------------")
NdefRecord = plus.android.importClass("android.nfc.NdefRecord");
NdefMessage = plus.android.importClass("android.nfc.NdefMessage");
let main = plus.android.runtimeMainActivity();
let intent = main.getIntent();
let that = this;
// console.log("action type:" + intent.getAction());
// console.log(package_TECH_DISCOVERED == intent.getAction());
if (package_TECH_DISCOVERED == intent.getAction()) {
// console.log(readyRead)
if (readyRead) {
// console.log("----------我在读1-------------")
that.read(intent);
readyRead = false;
}
}
},
read(intent) { // 读代码
// console.log("----------我在读read-------------")
toast('请勿移开标签正在读取数据');
let that = this;
// NFC id
let bytesId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
let nfc_id = that.byteArrayToHexString(bytesId);
// console.log('nfc_id:', nfc_id, 124565423454321234);
store.commit('setnfc_id', nfc_id);
// return nfc_id
toast('nfc_id:' + nfc_id);
let Parcelable = plus.android.importClass("android.os.Parcelable");
let rawmsgs = intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
//let rawmsgs = intent.getParcelableArrayExtra();
// console.log("数据" + rawmsgs)
if (rawmsgs != null && rawmsgs.length > 0) {
let records = rawmsgs[0].getRecords();
let result = records[0].getPayload();
let data = plus.android.newObject("java.lang.String", result);
// 写入vuex
// store.commit('setNfcReadTxt', data);
// toast('NFC 数据:' + data);
}
},
byteArrayToHexString: function (inarray) { // 将字节数组转换为字符串
let i, j, inn;
let hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
let out = "";
for (j = 0; j < inarray.length; ++j) {
inn = inarray[j] & 0xff;
i = (inn >>> 4) & 0x0f;
out += hex[i];
i = inn & 0x0f;
out += hex[i];
}
return out;
},
writeData: function () { // 更改写状态
if (noNFC) {
toast('请检查设备是否支持并开启 NFC 功能!');
return;
}
// 轮询条件
readyWriteData = true;
toast('请将NFC标签靠近!');
},
readData: function () { // 更改读状态
if (noNFC) {
toast('请检查设备是否支持并开启 NFC 功能!');
return;
}
// 轮询条件
readyRead = true;
// toast('请将NFC标签靠近!');
},
stopRead: function () {
readyRead = false;
},
// close: function(){
// },
setTxt: function (txt) {
if (noNFC) {
toast('请检查设备是否支持并开启 NFC 功能!');
return;
}
}
}
function toast(content) {
uni.showToast({
title: content,
icon: 'none'
})
}
然后再页面中调用
<template>
<view class="NFCread">
<!-- head -->
<view style="height: 1rpx"></view>
<view class="NFCread_top_box">
<image
@click="goback"
src="../../static/image/goback.png"
style="width: 18rpx; height: 37.5rpx; margin-right: 40rpx"
></image>
绑定NFC标签
</view>
<view class="NFCread_frame"> </view>
<!-- 靠近手机 -->
<view class="frame"></view>
<p class="frameone">请将手机靠近NFC标签</p>
<p class="frametwo">等待读取中...</p>
<view class="cancellation" @click="cancellationNFC"> 取消 </view>
</view>
</template>
<script>
//一定要引上面NFC的路径
import nfc from "@/utils/nfc.js";
import { getToolByNid } from "@/App/http.js";
import { mapState } from "vuex";
export default {
data() {
return {
nfc_id: "",
};
},
mounted() {
nfc.readData();
nfc.listenNFCStatus();
},
computed: {
nfc_ids() {
nfc.readData();
return this.$store.state.nfc_id;
},
},
watch: {
nfc_ids(val) {
var that = this;
this.nfc_id = val;
nfc.readData();
getToolByNid({
nid: val,
}).then((res) => {
console.log(res);
if (res[1].data.data == null) {
nfc.stopRead();
uni.redirectTo({
url: "/pages/SelectBinding/SelectBinding",
});
} else {
that.$store.commit("setAssignedInfo", res[1].data.data);
uni.redirectTo({
url: "/pages/Motor/Motor",
});
}
});
},
},
methods: {
goback() {
uni.redirectTo({
url: "/pages/home/index",
});
},
cancellationNFC() {
uni.redirectTo({
url: "/pages/home/index",
});
},
},
};
</script>