本文介绍了runOnUiThread没有调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

localChatManager.addIncomingListener { from, message, chat ->

                Log.v(TAG,"listener")


                //You can't modify views from non-UI thread.
                [email protected] { object :Runnable{
                    override fun run() {
                        Log.i(TAG,"runOnUiThread")
                     }
                } }
            }

我无法弄清为什么runOnUiThread不能正常运行,但是在该方法之外,一切都照常运行.

I am not able to figure out why runOnUiThread is not working but outside of that method everything is working as usual.

推荐答案

您正在做的是将lambda传递给runOnUiThread函数.它将运行该lambda,并创建一个从Runnable继承的object,然后对其不执行任何操作.也许您可以看到这样格式化的效果会更好一些(添加了一些额外的日志语句和说明):

What you are doing is passing in a lambda to the runOnUiThread function. It will run that lambda, and create an object that inherits from Runnable, and then do nothing with it. Maybe you can see that a little bit better if you format it like this (added some extra log statements and explanation):

runOnUiThread({
    Log.i(TAG, "This is run")
    object : Runnable {                    // This whole expression
        override fun run() {               // returns an object which
            Log.i(TAG, "runOnUiThread")    // is a Runnable, but does
        }                                  // not at any point invoke
    }                                      // its "run" method
    Log.i(TAG, "And so is this")
})

创建的object未分配给变量,并且从不使用.如果要将Runnable实例传递给runOnUiThread方法,可以通过将其放在runOnUiThread调用的括号内来实现:

The created object is not assigned to a variable, and is never used. If you want to pass in a Runnable instance to the runOnUiThread method, you can do that by just putting it inside the parentheses of the runOnUiThread call:

runOnUiThread(
        object : Runnable {
            override fun run() {
                Log.i(TAG, "runOnUiThread")
            }
        }
)

不过,使用runOnUiThread的最简单方法是使用SAM转换将lambda传递给它,然后在其中直接编写要执行的代码.

The simplest way to use runOnUiThread though is to pass in a lambda to it using SAM conversion, and writing the code you want to execute directly inside that.

runOnUiThread { 
    Log.i(TAG, "runOnUiThread") 
}

这是涵盖SAM转换的官方文档,在其示例中使用Runnable.

Here's the official documentation covering SAM conversions, which happens to use Runnable in its examples.

这篇关于runOnUiThread没有调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 15:14