我們先打開(kāi)
PDA手機(jī)
設(shè)置->掃描->Default->關(guān)閉(鍵盤(pán)方式輸出) 才能使用廣播監(jiān)聽(tīng)。

image.png
在你的uni-app項(xiàng)目里 新建一個(gè)公共組件 就叫 scan-code 吧,放到公共組件components中,目錄:components/scan-code/scan-code.vue這里就用到了廣播動(dòng)作和廣播數(shù)據(jù)標(biāo)簽
filter.addAction("android.intent.ACTION_DECODE_DATA")
intent.getStringExtra("barcode_string")
代碼里的filter.addAction里換成你的廣播動(dòng)作,intent.getStringExtra(里換成你的廣播標(biāo)簽
代碼如下:
<template>
<view class="content"></view>
</template>
<script>
var main,receiver,filter;
var _codeQueryTag = false;
export default {
data() {
return {
scanCode: ''
}
},
created: function (option) {
this.initScan()
this.startScan();
},
onHide:function(){
this.stopScan();
},
destroyed:function(){
/*頁(yè)面退出時(shí)一定要卸載監(jiān)聽(tīng),否則下次進(jìn)來(lái)時(shí)會(huì)重復(fù),造成掃一次出2個(gè)以上的結(jié)果*/
this.stopScan();
},
methods: {
initScan() {
let _this = this;
main = plus.android.runtimeMainActivity();//獲取activity
var IntentFilter = plus.android.importClass('android.content.IntentFilter');
filter = new IntentFilter();
filter.addAction("android.intent.ACTION_DECODE_DATA"); // 換你的廣播動(dòng)作
receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver',{
onReceive : function(context, intent) {
plus.android.importClass(intent);
let code = intent.getStringExtra("barcode_string");// 換你的廣播標(biāo)簽
_this.queryCode(code);
}});
},
startScan(){
main.registerReceiver(receiver,filter);
},
stopScan(){
main.unregisterReceiver(receiver);
},
queryCode: function(code){
//防重復(fù)
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>
頁(yè)面引用,只引用一次就好,我是index.vue 引用的,我的app的其他功能都是在這個(gè)頁(yè)面鏈接走的
直接上代碼:
切記:首頁(yè)往各個(gè)子頁(yè)面跳轉(zhuǎn)的時(shí)候 移除監(jiān)聽(tīng)事件uni.$off('scancodedate'),要不首頁(yè)的監(jiān)聽(tīng)會(huì)一直存在,就會(huì)出現(xiàn)首頁(yè)這個(gè)掃碼
uni.navigateTo({ 之前、之前、之前 uni.$off('scancodedate')
<template>
<view>
<view>你的頁(yè)面內(nèi)容</view>
<scan-code></scan-code>
</view>
</template>
<script>
import scanCode from "@/components/scan-code/scan-code.vue";
export default {
components: { scanCode },
data() {
return {}
}
onShow: function() {
var _this = this
uni.$off('scancodedate') // 每次進(jìn)來(lái)先 移除全局自定義事件監(jiān)聽(tīng)器
uni.$on('scancodedate',function(data){
console.log('你想要的code:', data.code)
})
}
}
其他的頁(yè)面引用方法:不需要再次引入scanCode因?yàn)槠渌捻?yè)面都是從首頁(yè)跳轉(zhuǎn)過(guò)來(lái)的,所以其他的頁(yè)面需要
onUnload() {
// 移除監(jiān)聽(tīng)事件
uni.$off('scancodedate')
}
onLoad() {
var _this = this
uni.$on('scancodedate',function(data){
// _this 這里面的方法用這個(gè) _this.code(data.code)
console.log('你想要的code:', data.code)
})
},
onUnload() {
// 移除監(jiān)聽(tīng)事件
uni.$off('scancodedate')
}