uniapp PDA设配扫码

组件

<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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值