<template>
	<view class="content"></view>
</template>

<script>
	export default {
		data() {
			return {
				activity: null,
				receiver: null,
				intentFilter: null
			}
		},
		created: function(option) {
			this.initScan()
			this.startScan();
		},
		onHide: function() {
			this.stopScan();
		},
		destroyed: function() {
			//页面退出时一定要卸载监听,否则下次进来时会重复，造成扫一次出2个以上的结果/
			this.stopScan();
		},
		methods: {
			initScan() {
				 // 非app不执行
				if (process.env.UNI_PLATFORM != 'app-plus') {
				  return true
				}
				
				let _this = this;
				this.activity = plus.android.runtimeMainActivity(); //获取activity
				var IntentFilter = plus.android.importClass('android.content.IntentFilter');
				this.intentFilter = new IntentFilter();
				this.intentFilter.addAction('android.intent.ACTION_DECODE_DATA') // 换你的广播动作
				this.receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
					onReceive: function(context, intent) {
						plus.android.importClass(intent);
						let content = intent.getStringExtra('barcode_string'); // 换你的广播标签
						uni.$emit('scancode', content)
					}
				});
			},
			startScan() {
				 // 非app不执行
				if (process.env.UNI_PLATFORM != 'app-plus') {
				  return true
				}
				
				this.activity.registerReceiver(this.receiver, this.intentFilter);
			},
			stopScan() {
				 // 非app不执行
				if (process.env.UNI_PLATFORM != 'app-plus') {
				  return true
				}
				
				this.activity.unregisterReceiver(this.receiver);
			}
		}
	}
</script>

<style>
</style>