Android实现USB扫码枪获取扫描二维码

USB 扫码枪会将扫描出来的内容转化为键盘事件,对应的就是Android中的KeyEvent事件,所以我们只需要在我们的activity中

重写dispatchKeyEvent方法

 private StringBuilder sb = new StringBuilder();
    private Handler myHandler = new Handler();
    boolean isScaning = false;
    int len = 0;
    int oldLen = 0;

    //二维码扫码
    @SuppressLint("RestrictedApi")
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int action = event.getAction();
        AppLogger.i("event"+event.getKeyCode());
        switch (action) {

            case KeyEvent.ACTION_DOWN:
                if (event.getKeyCode() == KeyEvent.KEYCODE_SHIFT_RIGHT) {
                    return super.dispatchKeyEvent(event);
                }
                int unicodeChar = event.getUnicodeChar();
                sb.append((char) unicodeChar);
                Log.e("MainActivity", "dispatchKeyEvent: " + unicodeChar + " " + event.getKeyCode());
                len++;
                startScan();
                return true;
            default:
                break;
        }
        return super.dispatchKeyEvent(event);
    }


    private void startScan() {
        if (isScaning) {
            return;
        }
        isScaning = true;
        timerScanCal();
    }

    private void timerScanCal() {
        oldLen = len;
        myHandler.postDelayed(scan, 100);
    }

    Runnable scan = new Runnable() {
        @Override
        public void run() {
            if (oldLen != len) {
                timerScanCal();
                return;
            }
            isScaning = false;
            if (sb.length() > 0) {
                AppLogger.i("扫码:" + sb.toString());
                sb.setLength(0);
            }
        }
    };

你可能感兴趣的:(安卓物联,二维码扫描)