How to talk to a Bluetooth keyboard?

Jeff picture Jeff · Nov 24, 2010 · Viewed 9.1k times · Source

I've written an Android app that connects to a Bluetooth keyboard. It connects through a BT socket to the keyboard and acquires the socket's input stream.

InputStream inStrm = socket.getInputStream();

Next I tried to read the input stream, but it says there are no bytes available.

int nBytesAvail = inStrm.available(); // always gives me 0

Or

int  dataByte = inStrm.read(); // always generates IOException

The exception says: Software caused connection to abort

If I try to write to the stream, I get another exception: Transport endpoint is not connected.

One of two things can be happening.

  1. My first fear is that there is the HID protocol to be spoken to the keyboard, and it will not divulge its secrets until I utter the proper incantation. Is that correct? Or should that be taken care of by the BT socket stack automatically? The socket stream seems to be a standard serial stream, and I'm not sure that's correct.

  2. My second fear is that since this is a Galaxy Tab, my problem might simply be that that particular part of the OS has been removed by Samsung (but would I still get a valid input stream from the socket connection?). It is widely reported that the US versions of the Tab simply will not connect to any BT HID using the standard Android BT utilities, although BT file transfers do work fine.

I suppose a third possibility is that I'm simply missing the keystrokes as they happen. I don't know how much buffering Java does of BT data coming in from a HID, but if the socket connection is made, the data should appear in the input stream, no?

I'm reluctant to put in much more time into this in case I'm going about it completely the wrong way (see #1), or it is doomed to fail (see #2).

Answer

mringwal picture mringwal · Sep 22, 2011

All normal Bluetooth keyboards implement the HID profile, which requires an L2CAP connection. Android so far only provides the ability to use RFCOMM connections. You would need to use the Native Development Kit and write your keyboard code in C to using bluez to achieve your goal. Have a look at apps that use the Nintendo WiiMote. The WiiMote also implements the HID profile.