简体   繁体   English

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

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

Try to connect with Bluetooth SPP to an ESP-32.尝试使用蓝牙 SPP 连接到 ESP-32。 Below is my code for the connect method in Android Studio.下面是我在 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. Not seeing any sort of connection attempt on my ESP monitor在我的 ESP 监视器上看不到任何类型的连接尝试
  2. I'm able to connect with a Bluetooth SPP Manager from the Play Store我可以从 Play 商店连接到蓝牙 SPP 管理器
  3. There are no errors being thrown except the "Fail" error at the end of the code chunk.除了代码块末尾的“失败”错误外,没有抛出任何错误。

Any help would be greatly appreciated.任何帮助将不胜感激。 I'm fairly new to Kotlin and Android programming so please forgive me if this code is hard to look at.我是 Kotlin 和 Android 编程的新手,所以如果这段代码很难看,请原谅我。

Replace the first line in the try with this.用这个替换 try 中的第一行。

device = bluetoothAdapter.getRemoteDevice(address)

Source: I'm the OP, and this fixed it资料来源:我是 OP,这解决了它

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

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