软件编程
位置:首页>> 软件编程>> Android编程>> Android 连接蓝牙扫码器无输入框的实现

Android 连接蓝牙扫码器无输入框的实现

作者:Uncle  发布时间:2023-05-06 02:37:34 

标签:Android,扫码,无输入框

Android 的APP 需要集成一个蓝牙扫码器, 特别的是,需要扫码的地方是没有输入框的(EditText),不能通过直觉上理解的通过对EditText输入事件进行监听处理,取得扫码结果。并且设备也没有提供SDK。

细想了一下, 蓝牙扫码器本质应该是个HID设备,相当于蓝牙键盘。而后豁然开朗。

每一次扫码应该会触发按键事件,通过监听当前Activity的按键事件,应该可以实现,无输入框的情况下取得扫码结果。

重载Activity中的dispatchKeyEvent实现按键监听。

@Override
   public boolean dispatchKeyEvent(KeyEvent event) {
       InputDevice inputDevice = event.getDevice();
       if (inputDevice != null) {
           int keyboardType = event.getDevice().getKeyboardType();
           String deviceName = event.getDevice().getName();
           boolean isVirtual = event.getDevice().isVirtual();
           //可以根据输入设备信息判断是否为特定扫码器输入
           if (!isVirtual) {
               scannerHelper.onScanerInput(event);
           }
       }
   }

通常扫码器在扫码结果后会追加一个结束字符,我的这个设备默认为回车。 所以接收到回车可以认为一个扫码结果“输入”完成。

public class ScannerHelper {
   private String buffer ="";
   private MainOneActivity mainOneActivity;
   public ScannerHelper(MainOneActivity mainOneActivity){
       this.mainOneActivity = mainOneActivity;
   }
   public void onScanerInput(KeyEvent event){
       if(event.getKeyCode() == KeyEvent.KEYCODE_ENTER){
           mainOneActivity.onScannerResult(buffer);//回调扫码结果
           buffer="";
       }else{
           if (event.getAction() == KeyEvent.ACTION_UP && event.isPrintingKey()){
               buffer +=  (char)event.getUnicodeChar();
           }
       }
   }
}

测试OK。

来源:https://www.cnblogs.com/uncleguo/archive/2022/02/25/15934821.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com