uniapp监听PDA激光扫描

我们先打开
PDA手机
设置->扫描->Default->关闭(键盘方式输出) 才能使用广播监听。

image.png

在你的uni-app项目里 新建一个公共组件 就叫 scan-code 吧,放到公共组件components中,目录:components/scan-code/scan-code.vue这里就用到了广播动作和广播数据标签

filter.addAction("android.intent.ACTION_DECODE_DATA")

intent.getStringExtra("barcode_string")

代码里的filter.addAction里换成你的广播动作,intent.getStringExtra(里换成你的广播标签

代码如下:

<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(){
/页面退出时一定要卸载监听,否则下次进来时会重复,造成扫一次出2个以上的结果/
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”); // 换你的广播动作
receiver = plus.android.implements(‘io.dcloud.feature.internal.reflect.BroadcastReceiver’,{
onReceive : function(context, intent) {
plus.android.importClass(intent);
let code = intent.getStringExtra(“barcode_string”);// 换你的广播标签
_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>

页面引用,只引用一次就好,我是index.vue 引用的,我的app的其他功能都是在这个页面链接走的

直接上代码:

切记:首页往各个子页面跳转的时候 移除监听事件uni.$off('scancodedate'),要不首页的监听会一直存在,就会出现首页这个扫码

uni.navigateTo({ 之前、之前、之前 uni.$off('scancodedate')

<template>  
    <view>  
        <view>你的页面内容</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. o f f ( ′ s c a n c o d e d a t e ′ ) / / 每 次 进 来 先 移 除 全 局 自 定 义 事 件 监 听 器 u n i . off('scancodedate') // 每次进来先 移除全局自定义事件监听器 uni. off(scancodedate)//uni.on(‘scancodedate’,function(data){
console.log(‘你想要的code:’, data.code)
})
}
}

其他的页面引用方法:不需要再次引入scanCode因为其他的页面都是从首页跳转过来的,所以其他的页面需要

onUnload() {
// 移除监听事件
uni.$off('scancodedate')
}

onLoad() {  
   var _this = this  
   uni.$on('scancodedate',function(data){  
        // _this 这里面的方法用这个 _this.code(data.code)  
    console.log('你想要的code:', data.code)  
   })  
},  
onUnload() {  
   // 移除监听事件      
   uni.$off('scancodedate')  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值