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.uj5u.com/yidong/433202.html
標籤:其他
上一篇:超簡單集成 HMS ML Kit 實作最大臉微笑抓拍
下一篇:Masonry的進階使用技巧
