最近项目遇到这样的需求,安卓系统收银机,需要无输入框焦点的时候监听usb的扫码枪扫描数据,应用的技术是uniapp集成到android原生里。刚开始一直用安卓写监听方法,然后再把扫码的数据抛回到uniapp上,但是调试的时候发现没这么理想,一个是因为页面是vue写的,原生打开这个小程序页面时,不能启动监听usb扫码事件,也许是我没用对方法哈。另外一个是uniapp和安卓宿主通讯的问题。 最后用uniapp监听键盘keypress事件,但uniapp没有针对android的监听keypress事件。如果是window是可以这样写:
window.addEventListener('keypress',function(e){
})
在安卓平台上只能用H5 native.js监听keyup事件,没有keypress事件,其实也是一样的效果,都能实现无输入框监听usb扫码枪数据(其实也是一种外接键盘)。还需要做keyCode进行转换,这里的键值对应表需要用安卓的才行
<template>
<view >
<text>输入内容:{
{inputString}}</text>
</view>
</template>
data() {
return {
inputString:'',
inputCache:'',
}
},
onLoad() {
plus.key.addEventListener("keyup",this.keypress);
},
methods: {
keypress(e){
// console.log('focusElement',this.focusElement)
//if(this.focusElement) return;
if(e.keyCode===66){
this.inputString = this.inputCache;
this.inputCache = '';
}else{
this.inputCache += this.keyValue(e.keyCode)
}
console.log('keypress argument:',e)
},
keyValue(keyCode){
switch(keyCode){
case 7:
return 0;
case 8:
return 1;
case 9:
return 2;
case 10:
return 3;
case 11:
return 4;
case 12:
return 5;
case 13:
return 6;
case 14:
return 7;
case 15:
return 8;
case 16:
return 9;
case 156:
return '-';
case 70:
return '=';
case 157:
return '+';
default :
return '' ;
}
},
}