Search code examples
javaandroidbarcodescanning

Block further scans in android


I'm scanning a barcode, put the String into an edittext and search with that. No problem.

My problem is, that when the barcode gets scanned, the action is executed about 3 times instead of jsut one time. I guess its because it needs some milliseconds to do the search and start the action but in this time the scanner sends some more scans (the same barcode) after.

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        Logger.i(TAG, "KeyCode: " + keyCode);
        switch(keyCode) {
        case KeyEvent.ACTION_DOWN:
            someAction();
            break;

        case KeyEvent.KEYCODE_ENTER:
            someAction()
            break;

        }
        return false;
    }

Scanning works fine, I just get 2 more keyevents after the scan actually was successful, so the whole process will be executed 2 more times...

Edit: I'm working with 2 different scanners, the first one sends the keyCode 0 the other one keyCode 66, thats why I handle both. The problem occurs with keyCode 0, I havent tested with the other scanner yet.


Solution

  • Create a state (boolean) to know when you need to handle the scanned barcode.

    Example: boolean mustHandleScan = true. When your scanned did recognise a barcode, change that boolean to false. And only do the search if the boolean is true. You can use a timer (maybe countdowntimer) to change the boolean to true after x seconds. This is an easy solution to implement, I'm using this too.