1. 程式人生 > 其它 >Android 連線藍芽掃碼器 無輸入框

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。