组件
<template>
<view>
<view class="content"></view>
</view>
</template>
<script>
var main, receiver, filter;
var codeQueryTag = false;
export default {
name: "xw-scan",
data() {
return {
scanCode: ''
}
},
created() {
this.initScan()
this.startScan();
},
onHide() {
this.stopScan();
},
destroyed() {
this.stopScan();
},
methods: {
initScan() {
console.log('initScan');
let that = this;
main = plus.android.runtimeMainActivity(); //获取activity
//var context = plus.android.importClass('android.content.Context'); //上下文
var IntentFilter = plus.android.importClass('android.content.IntentFilter');
filter = new IntentFilter();
//下面的android.intent.ACTION_DECODE_DATA改为自己的广播动作
filter.addAction("android.intent.ACTION_DECODE_DATA");
receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
onReceive: (context, intent) => {
console.log('onReceive');
plus.android.importClass(intent);
//下面的barcode_string改为自己的广播标签
let code = intent.getStringExtra("barcode_string");
that.queryCode(code);
}
});
},
startScan() {
console.log('startScan');
main.registerReceiver(receiver, filter);
},
stopScan() {
console.log('stopScan');
main.unregisterReceiver(receiver);
},
queryCode: function(code) {
console.log('queryCode');
if (codeQueryTag) return false;
codeQueryTag = true;
setTimeout(function() {
codeQueryTag = false;
}, 150);
//var id = code
var id = code.replace(/\s/g, "");
uni.$emit('xwscan', {
code: id
})
}
}
}
</script>
<style>
</style>
应用页面
<template>
<view>
扫描结果:{{input}}
<button type="default" @click="scanCode()">扫描</button>
<!-- #ifdef APP-PLUS -->
<xw-scan></xw-scan>
<!-- #endif -->
</view>
</template>
<script>
export default {
data() {
return {
input: ''
}
},
onLoad() {
},
onUnload() {
// #ifdef APP-PLUS
// 移除监听事件
uni.$off('xwscan')
// #endif
},
onShow() {
let that = this
// #ifdef APP-PLUS
uni.$off('xwscan') //移除全局自定义事件监听器
uni.$on('xwscan', (res)=> {
console.log('扫码结果:', res.code);
this.input = res.code
})
// #endif
},
methods: {
scanCode() {
uni.scanCode({
onlyFromCamera: true,
success: (res) => {
console.log('条码类型:' + res.scanType);
console.log('条码内容:' + res.result);
this.input = res.result
}
});
},
}
}
</script>
<style lang="scss" scoped>
</style>