简体   繁体   中英

Handling a bluetooth barcode scanner in Android

I have a simple android app, which allows the user to key in text into a textbox (a barcode), then press a button to send it to a server, and get a response.

This works fine.

Now I want to hook up a bluetooth barcode scanner and do all this without keying in the barcode or clicking on anything.

I am able to pair the devices easily enough. And I can scan a barcode into the textbox easily enough. But it wont send (just does a new line).

What I really want to do is something like this:

  1. Listen for any keydown events on this whole activity/view (not just the textbox). There are no other input boxes on this activity/view (sorry if a am getting these things mixed up)
  2. If it is from a soft keyboard, ignore.
  3. If it is from a hardware keyboard (ie a scanner). capture the value and store it in a variable.
  4. When the hardware keyboard sends a return or tab character, I send the collected barcode character to the server.

I'm not having much luck so far. Overriding the onKeyDown of the view doesnt capture anything. Nor does my attempt to use setOnKeyListener on the layout.

Can anyone offer some tips?

Thanks.

--- Edit ---

I have managed to override the dispatchKeyEvent, which does capture something, but only when the enter key (KEYCODE_ENTER) is pressed - not the rest of the barcode.

And by looking at the debug window, I can see there is an event which is capturing the entire barcode, but I have not been able to access it. What I'm getting in the debug window is:

I/ViewRootImpl: ViewRoot's KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_9, scanCode=10, metaState=0, flags=0x8, repeatCount=0, eventTime=821298066, downTime=821298066, deviceId=18, source=0x101 } to com.android.internal.policy.impl.PhoneWindow$DecorView{1f789e00 V.E..... R......D 0,0-1080,1920}

For now I am just using the dispatchKeyEvent - when I detect the enter key has been pressed, I send the barcode (it has been placed in the EditText). Not the ideal solution - I want to capture it all in a variable. But its the best I can do for now.

If anyone can improve on this, I'd much appreciate it.

 See if the code below can be of help to you: barcodeEditText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_ENTER: saveToDBMethod(); barcodeEditText.setText(""); barcodeEditText.requestFocus(); return true; default: break; } } return false; } }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM