Recently, I have made a project about external code scanning on Android devices. Here, I record the problem about obtaining content from Android USB code scanning gun
First of all, I use the USB HID code scanning gun, plug and play. Just have an EditText with focus on the interface to get the scanning content of the code scanning gun.
It's very simple, but today I'm talking about getting the scanning content of the code scanning gun without EditText.
The USB HID code scanning gun will convert the scanned content into keyboard events, corresponding to the KeyEvent event in Android, so we only need to use the
Override the onKeyDown method
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { checkLetterStatus(event); keyCodeToNum(keyCode); if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) { Log.e("Keyboard events", buffer.toString()); buffer.delete(0, buffer.length()); return true; } return false; }
We said above that the code scanning gun responds to our keyboard events, so when the code scanning gun scans a character, it is equivalent to pressing the corresponding key on our keyboard, that is, keyCode, so we only need to deal with this keyCode.
Next, I use checkLetterStatus() to check whether the case method and keyCodeToNum() convert the corresponding numbers and letters according to the corresponding keycode
//Check shift key private void checkLetterStatus(KeyEvent event) { int keyCode = event.getKeyCode(); if (keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT || keyCode == KeyEvent.KEYCODE_SHIFT_LEFT) { if (event.getAction() == KeyEvent.ACTION_DOWN) { //Press shift for upper case mCaps = true; } else { //Release shift for lowercase mCaps = false; } } } //Get the corresponding letters and numbers according to the keycode private void keyCodeToNum(int keycode) { if (keycode >= KeyEvent.KEYCODE_A && keycode <= KeyEvent.KEYCODE_Z) { if (mCaps) { buffer.append(map.get(keycode).toUpperCase()); } else { buffer.append(map.get(keycode)); } } else if ((keycode >= KeyEvent.KEYCODE_0 && keycode <= KeyEvent.KEYCODE_9)) { buffer.append(keycode - KeyEvent.KEYCODE_0); } else { //Do not process special symbols temporarily } }
There is a map in the above method, which is used to store letters
Map<Integer, String> map = new HashMap<>(); map.put(29, "a"); map.put(30, "b"); map.put(31, "c"); map.put(32, "d"); map.put(33, "e"); map.put(34, "f"); map.put(35, "g"); map.put(36, "h"); map.put(37, "i"); map.put(38, "g"); map.put(39, "k"); map.put(40, "l"); map.put(41, "m"); map.put(42, "n"); map.put(43, "0"); map.put(44, "p"); map.put(45, "q"); map.put(46, "r"); map.put(47, "s"); map.put(48, "t"); map.put(49, "u"); map.put(50, "v"); map.put(51, "w"); map.put(52, "x"); map.put(53, "y"); map.put(54, "z");
Finally, a StringBuffer is used to receive the processed data. That's about it!