本文主要是介绍uniapp 手持终端PDA扫码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
步骤一:查看广播名称(或者广播标签)和键值
在桌面中找到仓管通,进入软件设置,查看自己的广播名称和键值。(说明:每个手持机可能有所不同)
步骤二:代码实现环节
-
1.首先在components文件夹创建一个名为scancode组件
<template><view class="content"></view>
</template>
export default {name: "scancode",data() {return {activity: null,receiver: null,intentFilter: null};},created: function(option) {this.ksguangbo()this.initScan()setTimeout(() => {this.startScan();}, 1000)},onHide: function() {this.stopScan();},destroyed: function() {//一定要卸载监听,否则下次扫描时结果会重复,造成扫一次出2个以上的结果或者结果会不断连续叠加this.stopScan();},methods: {ksguangbo() { //发送广播var Intent = plus.android.importClass("android.content.Intent");var intent = new Intent("com.android.scannerservice.scan");var keyValue = "231112312";var main = plus.android.runtimeMainActivity();intent.putExtra("key", keyValue);main.sendBroadcast(intent);},initScan() {let _this = this;_this.activity = plus.android.runtimeMainActivity(); //获取运行时的主要活动console.log('扫码组件36行', _this.activity);var IntentFilter = plus.android.importClass('android.content.IntentFilter'); //导入类console.log('扫码组件38行', IntentFilter);_this.intentFilter = new IntentFilter(); //实例化一个意图过滤器_this.intentFilter.addAction('com.android.scannerservice.scan') //addAction添加动作 记得换你的com.android.scannerservice.scan广播动作或者广播名称//蓝牙//var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");//var BAdapter = new BluetoothAdapter.getDefaultAdapter();// _this.intentFilter.addAction(BAdapter.ACTION_STATE_CHANGED); //监听蓝牙// console.log('扫码组件44行', _this.intentFilter);//BroadcastReceiver广播接收器接口// implements 实现接口 onReceive实现接口的方法_this.receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {onReceive: function(context, intent) {console.log("58行", intent)plus.android.importClass(intent);let content = intent.getStringExtra('scannerdata'); // 换你手持机的广播键值 console.log('content', content)uni.$emit('scancodedate', content)},});},startScan() { //开始扫描this.activity.registerReceiver(this.receiver, this.intentFilter);console.log('开始扫描')},stopScan() { //结束扫描this.activity.unregisterReceiver(this.receiver);}}}
- 2.在页面中使用scancode组件
<view><scanCode></scanCode>
</view>
在生命周期函数--onShow实现监听,在onHide函数再次关闭监听(不用就关闭免得浪费开销)
/*** 生命周期函数--监听页面显示*/onShow() {// #ifdef APP-PLUSuni.$off('scancodedate');var _this = thisuni.$on('scancodedate', function(content) {console.log("扫描到的内容为:", content)var scanContent = content.replace('\n', '');_this.scanContent(scanContent);})// #endif},
/*** 生命周期函数--监听页面隐藏*/onHide() {// #ifdef APP-PLUSuni.$off('scancodedate');// #endif},
这篇关于uniapp 手持终端PDA扫码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!