我正在尝试Bluetooth Guide from google on Android

当尝试连接到另一台设备时,连接成功,但是之后,当我开始侦听传入的字节时,出现以下异常:socket closed: read return: -1
这是从Google指南复制的连接代码。

private inner class ConnectThread(device: BluetoothDevice) : Thread() {

private val mmSocket: BluetoothSocket? by lazy(LazyThreadSafetyMode.NONE) {
    device.createRfcommSocketToServiceRecord(MY_UUID)
}

public override fun run() {
    // Cancel discovery because it otherwise slows down the connection.
    mBluetoothAdapter?.cancelDiscovery()

    mmSocket?.use { socket ->
        // Connect to the remote device through the socket. This call blocks
        // until it succeeds or throws an exception.
        socket.connect()

        // The connection attempt succeeded. Perform work associated with
        // the connection in a separate thread.
        manageMyConnectedSocket(socket)
    }
}

// Closes the client socket and causes the thread to finish.
fun cancel() {
    try {
        mmSocket?.close()
    } catch (e: IOException) {
        Log.e(TAG, "Could not close the client socket", e)
    }
}
}

最佳答案

问题来自于Google指南上发布的代码。

问题是他们调用mmSocket?.use {},然后继续使用此套接字进行连接。 use()方法是一个非常有用的扩展功能,它使Disposable对象可以对它们执行操作,然后在操作结束时对其进行调用close()

在这种情况下,显然是一个错误。您不希望在建立连接后立即关闭套接字。

要使其工作,只需将mmSocket?.use {}替换为mmSocket?.let {},您就可以使用了。

希望谷歌将更新他们的指南。

10-08 12:05