4

I wanted to check programmatically that whether the input given by user is either from soft keyboard or the barcode scanner attached to the android tablet.

There is no edit text in activity where I want to apply this so please avoid providing solutions that are applicable through EditText.

Sachin Verma
  • 69
  • 1
  • 4
  • check this link https://stackoverflow.com/questions/29769204/detect-input-from-software-or-hardware-keyboard – AskNilesh Aug 30 '17 at 11:42
  • ok thanks but I wanted to know if in an activity in which there is no edittext but still user giving inputs from hardware keys. – Sachin Verma Aug 30 '17 at 11:51
  • 1
    If there is no `EditText`, then usually there is no input method editor (soft keyboard) showing, and therefore any input is coming from device buttons, Bluetooth keyboards, USB keyboards, etc. – CommonsWare Aug 30 '17 at 11:56
  • yes thank you that is one point I can check on and if I have barcode scanner – Sachin Verma Aug 30 '17 at 12:18

2 Answers2

1

With dispatchKeyEvent you can listen for any KeyEvent from the barcode scanner.

@Override
public boolean dispatchKeyEvent(KeyEvent e) {
// do something on input
   return false; // prevent default behaviour
}
Margerite
  • 31
  • 3
0

Use following code to read input/values from barcode scanner, so onKeyDown you need to override in your activity/dialog

String barcode="";
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    log("Key Down keyCode " + keyCode);
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        return super.onKeyDown(keyCode, event);
    } else if (keyCode == KeyEvent.KEYCODE_ENTER) {//if scanner doesn't return enter key code then make sure that any view must not have focus in window
        //write your code to process the scanned barcode input
        barcode = "";
    } else {
        Character input = (char) event.getUnicodeChar();
        log("Scanner Input " + input);
        if (Character.isDigit(input) || Character.isLetter(input)) {
            barcode += input;//concat the characters
        }
    }
    return true;
}
turbandroid
  • 2,296
  • 22
  • 30