如何在Android中配对(绑定)蓝牙设备后以编程方式连接到蓝牙设备

时间:2015-10-30 14:55:47

标签: java android sockets bluetooth

我一直在努力尝试使用键盘或遥控器等蓝牙设备连接到Android设备。更具体地说,当该程序第一次运行时,它将扫描蓝牙设备并尝试与它找到的一个配对并连接。我似乎已经尝试了一切可能的方法来实现这一点,但我只能配对设备,而不是完全连接它。 我已尝试过Android蓝牙指南和其他许多示例。一个一致性是我在BluetoothSocket调用connect时得到的javi.io错误。

java.io.IOException: read failed, socket might closed or timeout, read ret: -1
at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:505)
at android.bluetooth.BluetoothSocket.waitSocketSignal(BluetoothSocket.java:482)
at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:324)
at BTConnectThread.run(BTConnectThread.java:61)

我尝试过不同的UUID。有些我生成了自己从设备中拔出的其他人。我也尝试编写代码,假设两者都充当服务器,主要反映了我在这里所做的以及Android蓝牙指南中的内容。尝试过在设备上调用createBond()的所有变体。所有尝试都将设备配对/绑定但未连接。任何帮助是极大的赞赏。 `public BTConnectThread(BluetoothDevice bluetoothDevice){

    BluetoothSocket tempSocket = null;

    try {
       // tempSocket =        bluetoothDevice.createRfcommSocketToServiceRecord(WELL_KNOWN_UUID);
      //  tempSocket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(WELL_KNOWN_UUID);

        //Magic?
        Method method = bluetoothDevice.getClass().getMethod("createRfcommSocket",
            new Class[]{int.class});
        tempSocket = (BluetoothSocket) method.invoke(bluetoothDevice, 1);

    } catch (Exception e) {
        e.printStackTrace();
    }

    m_bluetoothSocket = tempSocket;

}

public void run() {

    //cancel discovery
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter != null)
        bluetoothAdapter.cancelDiscovery();

    //TODO: Try brute force approach. Loop until it connects.
    //TODO: Try a fallback socket.
    try {
        m_bluetoothSocket.connect();
        Log.d(TAG, "Connection Established");

    } catch (IOException connectException) {
        // Unable to connect; close the socket and get out
        Log.d(TAG, "Fail to connect!", connectException);
        try {
            m_bluetoothSocket.close();
        } catch (IOException closeException) {
            Log.d(TAG, "Fail to close connection", closeException);
        }
        return;
    }
}

public void cancel() {

    try {
        m_bluetoothSocket.close();
    } catch (IOException e) {

    }
}`

2 个答案:

答案 0 :(得分:2)

蓝牙连接需要创建3个以上的线程,因此您可以尝试使用https://android-arsenal.com/details/1/1859

答案 1 :(得分:0)

科特林

连接功能

    fun connect(btDevice: BluetoothDevice?){
        val id: UUID = btDevice?.uuids?.get(0)!!.uuid
        val bts = btDevice.createRfcommSocketToServiceRecord(id)
        bts?.connect()
    }

在主线程中调用

    val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
    val device = bluetoothAdapter.getRemoteDevice("your mac address")
    connect(device)