Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android get barcode scanner input without edittext

I have a physical barcode scanner and I want to get it's input, i.e the barcode, in the app without having a focused EditText.

I tried adding a KeyListener in my Activity. However, none of its implemented methods (onKeyUp, onKeyDown etc) was called.

Then I added the dispatchKeyEvent, which worked, but is never called as many times as the barcode length. Instead, before the barcode is read, some random button in my view gets focus from the barcode scanner.

String barcode = "";

@Override
public boolean dispatchKeyEvent(KeyEvent e) {
    char pressedKey = (char) e.getUnicodeChar();
    barcode += pressedKey;
    if (e.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
        Toast.makeText(getApplicationContext(), "barcode--->>>" + barcode, Toast.LENGTH_LONG)
                .show();
    }

    return super.dispatchKeyEvent(e);
}

I've seen a few questions out there in SO but none really gave a concrete answer.

like image 454
XeniaSis Avatar asked Jul 22 '16 16:07

XeniaSis


People also ask

How do I add a barcode scanner to my keyboard?

In order to use the Barcodescanner Keyboard you need to enable it. Do this by opening Android Settings , Language & keyboard and enable the input method named Barcode Keyboard by checking the box.


2 Answers

For me, for a barcode scanner (USB, reference STA pcs) works the next code:

@Override
public boolean dispatchKeyEvent(KeyEvent e) {

    if(e.getAction()==KeyEvent.ACTION_DOWN){
        Log.i(TAG,"dispatchKeyEvent: "+e.toString());
        char pressedKey = (char) e.getUnicodeChar();
        barcode += pressedKey;
    }
    if (e.getAction()==KeyEvent.ACTION_DOWN && e.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
        Toast.makeText(getApplicationContext(), 
            "barcode--->>>" + barcode, Toast.LENGTH_LONG)
        .show();

        barcode="";
    }

    return super.dispatchKeyEvent(e);
}
like image 173
Hpsaturn Avatar answered Sep 21 '22 15:09

Hpsaturn


First, thank you all. Since my App has to look up the barcode in the DB I had to not add the ENTER_KEY input to the Barcode String, also to prevent any focused button of going off I made the Method return false.

String barcode = "";
@Override
public boolean dispatchKeyEvent(KeyEvent e) {
    if(e.getAction()==KeyEvent.ACTION_DOWN
            && e.getKeyCode() != KeyEvent.KEYCODE_ENTER){ //Not Adding ENTER_KEY to barcode String
        char pressedKey = (char) e.getUnicodeChar();
        barcode += pressedKey;
    }
    if (e.getAction()==KeyEvent.ACTION_DOWN 
            && e.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
        Log.i(TAG,"Barcode Read: "+barcode);
        barcodeLookup(barcode);// or Any method handling the data
        barcode="";
    }
        return false;
}
like image 38
Jonathan A Melendez Avatar answered Sep 17 '22 15:09

Jonathan A Melendez