1、首先创建一个公用的PDA设备扫描组件
<template>
<view class="content"></view>
</template>
<script>
var main,receiver,filter;
var _codeQueryTag = false;
export default {
name: 'scan',
data() {
return {
scanCode: '123'
}
},
created: function (option) {
if(uni.getSystemInfoSync().platform == 'android'){
this.initScan()
this.startScan();
}
},
onHide:function(){
if(uni.getSystemInfoSync().platform == 'android'){
this.stopScan();
}
},
destroyed:function(){
if(uni.getSystemInfoSync().platform == 'android'){
/*页面退出时一定要卸载监听,否则下次进来时会重复,造成扫一次出2个以上的结果*/
this.stopScan();
}
},
methods: {
initScan() {
let _this = this;
main = plus.android.runtimeMainActivity();//获取activity
var IntentFilter = plus.android.importClass('android.content.IntentFilter');
filter = new IntentFilter();
//在PDA设备上直接替换自己的广播动作和广播标签
filter.addAction("nlscan.action.SCANNER_RESULT"); // 换你的广播动作,
receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver',{
onReceive : function(context, intent) {
plus.android.importClass(intent);
let code = intent.getStringExtra("SCAN_BARCODE1");// 换你的广播标签
_this.queryCode(code);
}});
},
startScan(){
//注册广播接收器
main.registerReceiver(receiver,filter);
},
stopScan(){
//注销广播接收器
main.unregisterReceiver(receiver);
},
queryCode: function(code){
//防重复
if(_codeQueryTag)return false;
_codeQueryTag = true;
setTimeout(function(){
_codeQueryTag = false;
},150);
var id = code
// console.log('id:', id)
uni.$emit('scancodedate',{code:id})
}
}
}
</script>
<style>
page {
background-color: #efeff4;
}
.content {
text-align: center;
}
</style>
2、在登录后第一个响应页面引入组件
import scan from '@/components/scan/scan.vue'
onLoad(){
if(uni.getSystemInfoSync().platform == 'android'){
console.log('安卓')
uni.$on('scancodedate',function(data){
// _this 这里面的方法用这个 _this.code(data.code)
console.log('你想要的code:', data.code)
})
}
}
3、在需要使用PDA功能页面直接使用
onShow(){
if(uni.getSystemInfoSync().platform == 'android'){
//PDA设备扫描监听
uni.$on('scancodedate',function(data){
//得到PDA设备扫描出的条码值
let scanCode=data.code;
}
}
}
onHide() {
if(uni.getSystemInfoSync().platform == 'android'){
// 移除监听事件
uni.$off('scancodedate');
}
},
onUnload() {
if(uni.getSystemInfoSync().platform == 'android'){
// 移除监听事件
uni.$off('scancodedate');
}
},