我正在尝试使用Activity.runOnUiThread(Runnable),但Android Studio似乎认为该功能不存在。我确保已导入“android.app.Activity”。

我正在尝试使用线程连接到蓝牙设备并读取数据。我已经列出了已配对的设备,单击已配对的设备中的一个会带我进入第二个屏幕,然后我可以在该屏幕中连接/断开所选设备的插座。连接和断开连接正在工作。

我现在正尝试将数据流从readThread内部类发送回UI线程,但无法使runOnUiThread正常工作。无论我做什么,runOnUiThread都不被识别。

package com.example.idxdatalogger

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.View
import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_second.*
import java.io.IOException
import java.io.InputStream
import java.util.*



class SecondActivity : AppCompatActivity() {
    var btAdapter: BluetoothAdapter? = null

    var data = arrayListOf<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)

        btAdapter = BluetoothAdapter.getDefaultAdapter()

        val position = (intent.getStringExtra("position"))!!.toInt()
        val uuid = UUID.fromString(intent.getStringExtra("UUID"))

        //textView.text = position.toString()
        //textView2.text = uuid.toString()

        val pairedDevices: Set<BluetoothDevice> = btAdapter!!.bondedDevices

        btDeviceLabel.text = pairedDevices.elementAt(position).name.toString()

        var inStream = connectStream(uuid, position, pairedDevices.elementAt(position), btAdapter)

        conStat(inStream)

        connectButton.setOnClickListener {
            inStream.start()
            conStat(inStream)
        }

        cancelButton.setOnClickListener {
            inStream.cancel()
            conStat(inStream)
            inStream = connectStream(uuid, position, pairedDevices.elementAt(position), btAdapter)
        }

    }

    /*
    change text and button visiblity for connect/disconnect buttons
     */
    fun conStat(inStream: connectStream) {
        if (inStream.socket!!.isConnected) {
            socketStatus.text = getString(R.string.connectionOpened)
            connectButton.visibility = View.INVISIBLE
            cancelButton.visibility = View.VISIBLE
        } else {
            socketStatus.text = getString(R.string.connectionClosed)
            connectButton.visibility = View.VISIBLE
            cancelButton.visibility = View.INVISIBLE
        }

    }

    class connectStream(
        private val uuid: UUID,
        private val position: Int,
        private val device: BluetoothDevice,
        private val adapter: BluetoothAdapter?
    ) : Thread() {
        val socket: BluetoothSocket? = device.createRfcommSocketToServiceRecord(uuid)

        override fun run() {

            adapter?.cancelDiscovery()

            try {
                socket?.connect()

                manageConnection().readThread(socket!!).start()
            } catch (e: IOException) {
                Log.i("SOCKET: ", "Failed to connect")
                Log.i("UUID: ", uuid.toString())
                Log.i("Device: ", device.name)
                Log.i("Address: ", device.address)
            }
        }

        fun cancel() {
            try {
                socket?.close()
            } catch (e: IOException) {
                Log.i("SOCKET: ", "Could not close socket")
            }
        }

    }

    class manageConnection() {
        private val MESSAGE_READ: Int = 0
        inner class readThread(socket: BluetoothSocket) : Thread() {
            private val inStream: InputStream = socket.inputStream
            private val inBuffer: ByteArray = ByteArray(1024)

            override fun run() {
                var readBytes: Int

                while (true) {
                    readBytes = try { inStream.read(inBuffer)
                    } catch (e: IOException) {
                        Log.d("IN_STREAM: ", "Input stream disconnected")
                        break
                    }
                    SecondActivity.runOnUiThread(Runnable {

                    })
                }
            }
        }
    }
}

编辑:

将我的程序重新编写为使用Thread(Runnable {}),而不是为每个线程使用单独的类实例。 runOnUiThread现在可以正常工作了。我已经在下面发布了更新的代码,但这还没有完全起作用。目前,我们可以考虑解决问题。
package com.example.idxdatalogger

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.util.Log
import android.view.View
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.*
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_second.*
import java.io.IOException
import java.io.InputStream
import java.util.*

/*

 */
class SecondActivity : AppCompatActivity() {
    var btAdapter: BluetoothAdapter? = null
    var data = arrayListOf<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)

        btAdapter = BluetoothAdapter.getDefaultAdapter()

        val position = (intent.getStringExtra("position"))!!.toInt()
        val uuid = UUID.fromString(intent.getStringExtra("UUID"))

        val pairedDevices: Set<BluetoothDevice> = btAdapter!!.bondedDevices
        val device = pairedDevices.elementAt(position)

        btDeviceLabel.text = pairedDevices.elementAt(position).name.toString()

        val socket: BluetoothSocket? = device.createRfcommSocketToServiceRecord(uuid)

        //var inStream = connectStream(uuid, position, pairedDevices.elementAt(position), btAdapter)
        conStat(socket!!)


        val inStream: InputStream = socket.inputStream
        val inBuffer: ByteArray = ByteArray(1024)

        var readBytes : Int

        connectButton.setOnClickListener {
            //connect to device
            Thread(Runnable {
                kotlin.run {
                    btAdapter?.cancelDiscovery()
                    try {
                        socket.connect()
                        runOnUiThread(Runnable { conStat(socket) })
                        //read stream
                        Thread(Runnable{
                            while(true) {
                                readBytes = try {
                                    inStream.read(inBuffer)
                                } catch (e: IOException) {
                                    Log.d("IN_STREAM: ", "input stream disconnected")
                                    break
                                }
                                //return stream information to UI thread
                                runOnUiThread(Runnable {
                                    data.add(inBuffer.toString())
                                    dataList.adapter = dataListAdapter(this,data)
                                    dataList.visibility = View.VISIBLE
                                })
                            }
                        }).start()
                    } catch (e: IOException) {
                        Log.i("SOCKET: ", "Failed to connect")
                        Log.i("UUID: ", uuid.toString())
                        Log.i("Device: ", pairedDevices.elementAt(position).name)
                        Log.i("Address: ", pairedDevices.elementAt(position).address)
                    }
                }
            }).start()

        }

        cancelButton.setOnClickListener {
            //close socket connection
            Thread(Runnable {
                try {
                    socket.close()
                } catch (e: IOException) {
                    Log.i("SOCKET: ", "Could not close socket")
                }
                runOnUiThread(Runnable {
                    conStat(socket)
                    val intent = Intent(this, MainActivity::class.java)
                    startActivity(intent)
                })
            }).start()
        }
    }

    /*
    change text and button visiblity for connect/disconnect buttons
     */
    fun conStat(socket : BluetoothSocket) {
        if (socket.isConnected) {
            socketStatus.text = getString(R.string.connectionOpened)
            connectButton.visibility = View.INVISIBLE
            cancelButton.visibility = View.VISIBLE
        } else {
            socketStatus.text = getString(R.string.connectionClosed)
            connectButton.visibility = View.VISIBLE
            cancelButton.visibility = View.INVISIBLE
        }
    }

最佳答案

您必须将inner添加到manageConnection类,然后才可以使用runOnUiThread {}

关于android-studio - Kotlin:runOnUiThread尚未解决的引用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57330607/

10-10 00:55