<template>
	<view class="content">
		<keyboard-listener @keydown="keyDown" @keyup="keyUp"></keyboard-listener>
	</view>
</template>
 
<script>
	import keyboardListener from 'uniapp-keyboard-listener'
	export default {
		components: {
			keyboardListener
		  },
		data() {
			return {
				activity: null,
				receiver: null,
				intentFilter: null,
				sPtime: 0,
				keys:{
					'TVNetwork': 'leftKey',
					'TVAntennaCable': 'rightKey',
					'TVSatelliteToggle': 'midKey'
				}
			}
		},
		created: function(option) {
			this.initScan()
			this.startScan();
		},
		onHide: function() {
			this.stopScan();
		},
		destroyed: function() {
			//页面退出时一定要卸载监听,否则下次进来时会重复,造成扫一次出2个以上的结果/
			this.stopScan();
			this.sPtime = 0
		},
		methods: {
			keyDown(e){
				if(!this.sPtime){
					this.sPtime = e.timeStamp
				}
				this.$emit('onKeyDown',this.keys[e.key]||e.key,e)
			},
			keyUp(e){
				const len = e.timeStamp - this.sPtime
				this.sPtime = 0
				this.$emit('onKeyUp',this.keys[e.key]||e.key,e)
			},
			initScan() {
				let _this = this;
				/* #ifdef APP-PLUS */
				this.activity = plus.android.runtimeMainActivity(); //获取activity
				var context = plus.android.importClass('android.content.Context'); //上下文
				var IntentFilter = plus.android.importClass('android.content.IntentFilter');
				this.intentFilter = new IntentFilter();
				this.intentFilter.addAction('nlscan.action.SCANNER_RESULT') // 换你的广播动作
				this.receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
					onReceive: function(context, intent) {
						console.log("intent",intent)
						plus.android.importClass(intent);
						let content = intent.getStringExtra('SCAN_BARCODE1'); // 换你的广播标签
						
						uni.$emit('scancodedate', content)
					}
				});
				/* #endif */
			},
			startScan() {
				/* #ifdef APP-PLUS */
				this.activity.registerReceiver(this.receiver, this.intentFilter);
				/* #endif */
			},
			stopScan() {
				/* #ifdef APP-PLUS */
				this.activity.unregisterReceiver(this.receiver);
				/* #endif */
			}
		}
	}
</script>
 
<style>
</style>