BluetoothSocket.connect 没有引发异常,但我没有连接



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

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 Store中连接蓝牙SPP管理器
  3. 除了"失败"之外,没有抛出任何错误。

任何帮助都将非常感激。我对Kotlin和Android编程相当陌生,所以如果这段代码很难看,请原谅我。

将try中的第一行替换为this

device = bluetoothAdapter.getRemoteDevice(address)

来源:我是OP,这修正了它

最新更新