BluetoothSocket.connect 没有抛出异常,但我没有连接

BluetoothSocket.connect doesn't throw an exception, but I'm not connected

尝试使用蓝牙 SPP 连接到 ESP-32。下面是我在 Android Studio 中连接方法的代码。

private fun bluetoothConnect() {
    var address : String? = null
    var uuids : Array<ParcelUuid>? = null
    val pairedDevices : Set<BluetoothDevice> = bluetoothAdapter.getBondedDevices()
    for (item in pairedDevices) {
        if(item.name == "Test"){
            address = item.address
            uuids = item.uuids
        }
    }

    val uuid : UUID? = uuids?.get(0)?.uuid
    Log.d("Bluetooth", "UUID: "+uuid.toString())
    try {
        bluetoothAdapter.getRemoteDevice(address)
        socket = device?.createInsecureRfcommSocketToServiceRecord(uuid)
        socket?.connect()
    } catch (e : IOException) {
        Log.e("Bluetooth", "Connection failed")
    }

    if (socket?.isConnected == true) {
        Log.i("Bluetooth", "Success")
    } else {
        Log.e("Bluetooth", "Fail")
    }
}
  1. 在我的 ESP 监视器上没有看到任何类型的连接尝试
  2. 我可以从 Play 商店连接蓝牙 SPP 管理器
  3. 除了代码块末尾的“失败”错误外,没有抛出任何错误。

如有任何帮助,我们将不胜感激。我对 Kotlin 和 Android 编程还很陌生,所以如果这段代码很难看,请原谅我。

用这个替换 try 中的第一行。

device = bluetoothAdapter.getRemoteDevice(address)

资料来源:我是 OP,这解决了问题