简体   繁体   English

无法将蓝牙键盘连接到Android设备

[英]Not able to connect a Bluetooth Keyboard to an android device

I am trying to programmatically connect an Android phone to a Bluetooth device (which is already paired). 我正在尝试以编程方式将Android手机连接到蓝牙设备(已配对)。 I am using createRfcommSocketToServiceRecord(UUID) method in a thread. 我在一个线程中使用createRfcommSocketToServiceRecord(UUID)方法。

I know the Bluetooth keyboard is a HID device so I am using UUID as 我知道蓝牙键盘是HID设备所以我使用的是UUID

00001124-0000-1000-8000-00805f9b34fb 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. 上面的方法返回一个BluetoothSocket对象,但是当调用bluetoothSocket.connect()时,它无法连接到HID设备。 It gives IOException: discovery failed 它给出IOException:发现失败

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? 是否只能在Android中使用此方法连接Rfcomm而非HID设备? 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. 我在这个应用程序中使用三星Galaxy S3与Android 4.1配对(从设置)我可以在一些内置的应用程序,如短信,电子邮件等使用蓝牙键盘键入。在我看来,连接到它应该是可能的,但我我不确定我是否使用了正确的方法。 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) { }
    }
}

Is is only possible to connect Rfcomm and not HID devices using this approach in Android? 是否只能在Android中使用此方法连接Rfcomm而非HID设备?

Yes, unfortunately. 是的,很不幸的。 The naming of the java methods makes it quite clear that only rfcomm is supported. java方法的命名使得很清楚只支持rfcomm。 HID most likely operates on raw l2cap. HID最有可能使用原始l2cap。

Try using InputDevice or takeKeyEvents to get keypress data in your app. 尝试使用InputDevicetakeKeyEvents来获取应用中的按键数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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