Reputation: 1095
So I have the following code which differentiates between soft keyboard entry and a Bluetooth barcode scanner...
if(event.getAction()==KeyEvent.ACTION_DOWN){
if(event.getDeviceId()==-1) //from soft keyboard
return super.dispatchKeyEvent(event);
char pressedKey = (char) event.getUnicodeChar();
barCode += pressedKey;
}
if (event.getAction()==KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
if(event.getDeviceId()==-1) //from keyboard
return super.dispatchKeyEvent(event);
String giftCardUPC = barCode.replaceAll("[^\\d.]", "");
fragmentProShopGiftCard.etUPCCode.setText(giftCardUPC);
barCode="";
}
the idea is that the barcode scanner has a device ID and the soft keyboard does not. The problem now is I have an activity that supports both a HARD bluetooth keyboard, soft keyboard (if they don't use a hard keyboard), as well as a barcode scanner.
Is there any way to differentiate between the 2 hardware devices on dispatchKeyEvent?
Upvotes: 1
Views: 936
Reputation: 1095
Here's what I ended up doing...I noticed that the barcode scanner's first entry was always a KeyCode of KEYCODE_LEFT_SHIFT....
String barCode = "";
boolean barCodeMode = false;
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if(event.getAction()==KeyEvent.ACTION_DOWN){
if(event.getDeviceId()==-1) { //from soft keyboard
return super.dispatchKeyEvent(event);
}else if(event.getKeyCode() == KeyEvent.KEYCODE_SHIFT_LEFT || barCodeMode){ //from barcode scanner
barCodeMode = true;
char pressedKey = (char) event.getUnicodeChar();
barCode += pressedKey;
}else{ //from hard keyboard
return super.dispatchKeyEvent(event);
}
}
if (event.getAction()==KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
if(event.getDeviceId()==-1) { //from soft keyboard
return super.dispatchKeyEvent(event);
}else if(barCodeMode){ //from barcode scanner
String giftCardUPC = barCode.replaceAll("[^\\d.]", "");
fragmentProShopGiftCard.etUPCCode.setText(giftCardUPC);
barCode="";
barCodeMode = false;
}else{ //from hard keyboard
return super.dispatchKeyEvent(event);
}
}
}
Upvotes: 1
Reputation: 1284
If there are other fields in the activity (or a previous activity or fragment) where the user is expected to perform manual input, you could check and save the device ID there, and later compare it to the device ID used for the input you're interested in.
Another possibility would be to record the timing of the key events. A barcode reader will be much faster than anyone can type.
Upvotes: 0