Android蓝牙套接字已关闭:阅读返回:-1

时间:2018-10-10 20:16:26

标签: android kotlin bluetooth

我正在尝试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)
    }
}
}

1 个答案:

答案 0 :(得分:0)

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

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

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

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

希望Google会更新其指南。

相关问题