Kotlin:runOnUiThread 未解决的引用

7
我试图使用Activity.runOnUiThread(Runnable)方法,但Android Studio似乎认为该函数不存在。我已确保导入了“android.app.Activity”。
我正在尝试使用线程连接到蓝牙设备并读取数据。我列出了配对的设备,并单击其中一个配对的设备会将我带到第二个屏幕,在那里我可以连接/断开选定设备的套接字。连接和断开功能正常。
我现在正在尝试从readThread内部类将数据流发送回UI线程,但无论我怎么做,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
        }
    }
4个回答

8

SecondActivity.runOnUiThread(...)是错误的,因为你正在对一个类调用方法,而runOnUiThread()方法不是静态的。你需要在Activity类的一个实例上调用此方法,而不是在类本身上调用。


我意识到那不正确,但无论我做什么它都告诉我runOnUiThread是未解决的引用。 - KjerfulCoder

1
请看这里的runOnUiThread签名:
    /**
 * Runs the specified action on the UI thread. If the current thread is the UI
 * thread, then the action is executed immediately. If the current thread is
 * not the UI thread, the action is posted to the event queue of the UI thread.
 *
 * @param action the action to run on the UI thread
 */
public final void runOnUiThread(Runnable action) {
    if (Thread.currentThread() != mUiThread) {
        mHandler.post(action);
    } else {
        action.run();
    }
}

很明显这不是一个静态方法,所以你不能像这样把它当作静态方法来调用:
SomeActivity.runOnUiThread {}

一个解决方法可以是将SecondActivity作为一个实例传递,然后轻松地对你的活动实例进行任何操作。

class myClass(val activity : Activity){

    fun someMethod(){
         activity.runOnUithread{}
        }
}

1

如果你想从后台线程运行runOnUiThread,你可以使用以下代码:

Handler mainHandler = new Handler(Looper.getMainLooper());

Runnable myRunnable = new Runnable() {
    @Override 
    public void run() {....}
};
mainHandler.post(myRunnable);

你不需要在这种情况下使用活动(Activity),因为你的Thread类不一定要在活动(Activity)中。另外,尝试使用协程(Couroutines)、RxKotlin、Google.Tasks和AsyncTask来更好地处理线程。

这是关于Java的话题,例如你所拥有的Kotlin语言。Java和Kotlin在很多方面都非常不同。 - James Smith

-1
你需要在你的manageConnection类中添加inner,然后就可以直接使用runOnUiThread {}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接