温馨提示:本文翻译自stackoverflow.com,查看原文请点击:multithreading - How to start a thread that is defined in a private inner class?

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

发布于 2020-03-27 12:09:16

在Android开发者网站上找到了如何使用单独的读取线程从Bluetooth套接字读取数据的示例读取线程在私有内部类“ 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()
}

但这会立即产生错误:

内部类ConnectedThread的构造方法只能由包含类的接收者调用

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

查看更多

查看更多

提问者
user1725145
被浏览
69
Francesc 2019-07-04 00:15

ConnectedThread是的内部类,MyBluetoothService因此无法在的实例外部实例化MyBluetoothService

像这样更改(删除private inner):

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

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