uniapp开发安卓app 实现nfc读卡功能
<template><view class="content"><view class="box"><view class="box_right"><view class="xiuxii_item"><view class="xinxi_zuo"><span class="rightLabel">车牌号:</
·
<template>
<view class="content">
<view class="box">
<view class="box_right">
<view class="xiuxii_item">
<view class="xinxi_zuo"><span class="rightLabel">车牌号:</span></view>
<view class="xinxi_you">{{loadForm.carNo}}</view>
</view>
<view class="xiuxii_item">
<view class="xinxi_zuo"><span class="rightLabel">货名:</span></view>
<view class="xinxi_you">{{loadForm.productName}}</view>
</view>
<view class="xiuxii_item">
<view class="xinxi_zuo"><span class="rightLabel">客户单位:</span></view>
<view class="xinxi_you">{{loadForm.userName}}</view>
</view>
<view class="xiuxii_item">
<view class="xinxi_zuo"><span class="rightLabel">额定载重(吨):</span></view>
<view class="xinxi_you">{{loadForm.weight}}</view>
</view>
</view>
</view>
<view class="btn">
<button type="warn" class="goodsBtn" @click="loadingCompleted">装载完成</button>
</view>
</view>
</template>
<script>
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 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']
];
let readyRead = false;
// let readyRead = false;
let nfc = {
nfcGetId: function(obj) {
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'
// })
return;
}
if (!nfcAdapter.isEnabled()) {
uni.showToast({
title: '请在系统设置中先启用NFC功能!',
icon: 'none'
});
return;
}
readyRead = true;
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(function() {
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());
// debugger
if (package_TECH_DISCOVERED == intent.getAction()) {
readyRead = true;
if (readyRead) {
// uni.showToast({
// title: '请勿移开标签正在读取数据',
// icon: 'none'
// });
let that = this;
// NFC id
let bytesId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
// console.log('id=' + bytesId)
let nfc_id = nfc.byteArrayToHexString(bytesId);
console.log('nfc_id:', nfc_id);
// uni.showToast({
// title: nfc_id,
// icon: 'success',
// duration: 2000
// });
// uni.showToast({
// title: '卡片读取成功',
// icon: 'success',
// // duration: 2000
// });
obj.success(nfc_id);
readyRead = false;
}
}
}, 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) {
//开启前台调度系统
nfcAdapter.enableForegroundDispatch(main, pendingIntent, intentFiltersArray, techListsArray);
}
});
nfcAdapter.enableForegroundDispatch(main, pendingIntent, intentFiltersArray, techListsArray);
// 监听事件,触发条件
// readyRead = true;
// uni.showToast({
// title: '请将NFC标签靠近!',
// icon: 'none'
// });
} catch (e) {
// console.error(e);
obj.fail(e);
} finally {
obj.complete();
}
},
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 = inarray.length - 1; j > -1; --j) {
inn = inarray[j] & 0xff;
i = (inn >>> 4) & 0x0f;
out += hex[i];
i = inn & 0x0f;
out += hex[i];
}
return out;
}
}
export default {
onLoad: function(option) {
plus.screen.lockOrientation('landscape-primary');
// console.log('onLoad');
},
onNavigationBarButtonTap(e) {
// console.log("success")
uni.redirectTo({
url: '/pages/index/x_index'
});
},
data() {
return {
nowWeek: '',
nowDate: '',
time: '',
loadForm: {
billNo: '',
carNo: '',
productName: '',
address: '',
siteName: '',
userName: '',
manager: '',
weight: '',
note: '',
},
userId: '',
username: '',
}
},
methods: {
// 获取最新时间
setNowTimes() {
var myDate = new Date;
var year = myDate.getFullYear(); //获取当前年
var mon = myDate.getMonth() + 1; //获取当前月
var date = myDate.getDate(); //获取当前日
// var h = myDate.getHours();//获取当前小时数(0-23)
// var m = myDate.getMinutes();//获取当前分钟数(0-59)
// var s = myDate.getSeconds();//获取当前秒
var week = myDate.getDay();
var weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
// console.log(year, mon, date, weeks[week])
this.time = weeks[week] + " " + year + "年" + mon + "月" + date + '日'
},
// 读取nfc
setNfcId() {
var that = this
// that.getAppUser()
// var id = that.userId
// var username = that.username
nfc.nfcGetId({
success: function(data) {
var str = data
var newStr = str //.split('').reverse().join('')
that.id = newStr
that.$func.api(
that.$apiConfig.getAppUser(), {},
function(ret) {
uni.showToast({
title: ret.data.code,
icon: 'none'
});
if(ret.data.code == '2000'){
console.log(ret.data.data.id)
console.log(ret.data.data.name)
that.$func.api(
that.$apiConfig.getInfo(), {
"number": newStr,
"forklifter": ret.data.data.id,
"forkliftName": ret.data.data.name
},
function(res) {
if (res.statusCode == '200') {
if (!res.data.obj || res.data.status == false) {} else {}
} else {}
},
function(err) {}
);
} else if(ret.statusCode == '302'){
uni.showToast({
title: '登录过期,请重新登录',
icon: 'none'
});
uni.setStorageSync('accessToken', '');
setTimeout(() => {
uni.redirectTo({
url: '/pages/login/login'
});
}, 1000);
}
}, function(err) {}, "", "", "", "", "body", '')
},
fail: function(data) {
uni.showToast({
title: '读取失败',
icon: 'none',
duration: 2000
});
// console.log('22222')
},
complete: function(data) {}
});
},
},
created() {
// this.setNowTimes()
this.setNfcId()
},
// 销毁监听事件 不然退出当前页面后依然会继续读卡
beforeDestroy() {
// clearInterval(this.timer)
plus.globalEvent.removeEventListener('newintent', function() {
// console.log('newintent 2222');
});
plus.globalEvent.removeEventListener('pause', function(e) {
// console.log('pause 2222');
});
plus.globalEvent.removeEventListener('resume', function(e) {
// console.log('resume 222');
});
// clearInterval(this.timeRunner)
// clearInterval(this.setNfcId)
},
}
</script>
<style>
</style>
打包时权限要加上
"orientation" : [ "landscape-primary", "landscape-secondary" ], //重力感应、横竖屏配置
/* android打包配置 */
"android" : {
"permissions" : [
"<uses-feature android:name=\"android.hardware.camera\"/>",
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_COARSE_LOCATION\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\"/>",
"<uses-permission android:name=\"android.permission.CALL_PHONE\"/>",
"<uses-permission android:name=\"android.permission.CAMERA\"/>",
"<uses-permission android:name=\"android.permission.CAPTURE_AUDIO_OUTPUT\"/>",
"<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>",
"<uses-permission android:name=\"android.permission.FLASHLIGHT\"/>",
"<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>",
"<uses-permission android:name=\"android.permission.MODIFY_AUDIO_SETTINGS\"/>",
"<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>",
"<uses-permission android:name=\"android.permission.NFC\"/>",
"<uses-permission android:name=\"android.permission.READ_CONTACTS\"/>",
"<uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\"/>",
"<uses-permission android:name=\"android.permission.READ_LOGS\"/>",
"<uses-permission android:name=\"android.permission.VIBRATE\"/>",
"<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>",
"<uses-permission android:name=\"android.permission.WRITE_CONTACTS\"/>",
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>"
],
"abiFilters" : [ "armeabi-v7a", "arm64-v8a", "x86" ]
},
更多推荐
已为社区贡献1条内容
所有评论(0)