I am trying to programmatically connect an Android phone to a Bluetooth device (which is already paired). I am using createRfcommSocketToServiceRecord(UUID) method in a thread.
I know the Bluetooth keyboard is a HID device so I am using UUID as
00001124-0000-1000-8000-00805f9b34fb
The above method returns a BluetoothSocket object, but it fails to connect to the HID device, when bluetoothSocket.connect() is called. It gives IOException: discovery failed
I have searched about this a lot, but no clue how to fix this.
Is it only possible to connect Rfcomm and not HID devices using this approach in Android? If so, then what alternate approach should I use for this? I am using Samsung Galaxy S3 with Android 4.1 in this application and after pairing (from settings) I could type using the Bluetooth keyboard in some inbuilt apps like SMS, Email etc. It seems to me that connecting to it should be possible, but I am not sure if I am using the right approach. I want to read the keypress serial data in my app.
Here's the code which I am using:
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
try {
tmp = device.createRfcommSocketToServiceRecord(mUUID);
} catch (IOException e) {
e.printStackTrace();
}
mmSocket = tmp;
}
public void run() {
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
Log.d(TAG, "ConnectThread connection successful");
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
Yes, unfortunately. The naming of the java methods makes it quite clear that only rfcomm is supported. HID most likely operates on raw l2cap.
Try using InputDevice or takeKeyEvents to get keypress data in your app.