如何启动在私有内部 class 中定义的线程?

How to start a thread that is defined in a private inner class?

我在 the Android developer website 上找到了这个关于如何使用单独的读取线程从蓝牙套接字读取数据的示例。读线程定义在private inner class "ConnectedThread".

class MyBluetoothService(
        // handler that gets info from Bluetooth service
        private val handler: Handler) {

    private inner class ConnectedThread(private val mmSocket: BluetoothSocket) : Thread() {

        private val mmInStream: InputStream = mmSocket.inputStream
        private val mmOutStream: OutputStream = mmSocket.outputStream
        private val mmBuffer: ByteArray = ByteArray(1024) // mmBuffer store for the stream

        override fun run() {
            var numBytes: Int // bytes returned from read()

            // Keep listening to the InputStream until an exception occurs.
            while (true) {
                // Read from the InputStream.
                numBytes = try {
                    mmInStream.read(mmBuffer)
                } catch (e: IOException) {
                    Log.d(TAG, "Input stream was disconnected", e)
                    break
                }

                // Send the obtained bytes to the UI activity.
                val readMsg = handler.obtainMessage(
                        MESSAGE_READ, numBytes, -1,
                        mmBuffer)
                readMsg.sendToTarget()
            }
        }
 //Other functions like write, cancel that I omitted from this example

}

所以我在MyBluetoothService中添加了一个函数来启动读取线程:

 @JvmStatic
fun read(){
val reader = ConnectedThread(myBluetoothSocket)
Reader.start()
}

但这会立即出错:

Constructor of inner class ConnectedThread can be called only with receiver of containing class

我应该如何从示例代码启动线程?

您的 ConnectedThreadMyBluetoothService 的内部 class,因此无法在 MyBluetoothService.

的实例之外实例化

改成这样(去掉private inner):

class ConnectedThread(private val mmSocket: BluetoothSocket) : Thread() {

您必须通过其他方式访问该服务,或者在您的服务中创建一个实例化线程的工厂方法 returns。