Android - 如何在runOnUiThread 中将数据传递给Runnable? [英] Android - howto pass data to the Runnable in runOnUiThread?

查看:33
本文介绍了Android - 如何在runOnUiThread 中将数据传递给Runnable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更新一些 UI 并在 UI 线程内使用 runOnUiThread
现在 UI 的数据来自另一个线程,这里用 data 表示.

I need to update some UI and do it inside of the UI thread by using runOnUiThread
Now the data for the UI comes from the other Thread, represented by data here.

如何将数据传递给 Runnable,以便它们可用于更新 UI?Android 似乎不允许直接使用数据.有没有优雅的方法来做到这一点?

How can i pass the data to the Runnable, so tht they can be used to update the UI? Android doesn't seem to allow using data directly. Is there an elegant way to do this?

public void OnNewSensorData(Data data) {

    runOnUiThread(new Runnable() {
        public void run() {
            //use data
        }
    });
}

我的解决方案是在可运行文件中创建一个字段private Data sensordata,并为其分配数据.这仅适用于原始 Data data 是最终的.

My solution was creating a fioeld private Data sensordata inside of the runnable, and assigning data to it. This works only, if the original Data data is final.

public void OnNewSensorData(final Data data) {

    runOnUiThread(new Runnable() {
        private Data sensordata = data;
        public void run() {
            //use sensordata which is equal to data
        }
    });
}

推荐答案

你发现的问题是

Java 中的内部类捕获(关闭")其中的词法范围它们被定义.但它们只捕获声明为最终"的变量.

Inner classes in Java capture ("close over") the lexical scope in which they are defined. But they only capture variables that are declared "final".

如果这很清楚,这里有一个很好的细节讨论:不能参考到在不同方法中定义的内部类中的非最终变量

If this is clear as mud, there's a good discussion of the details here: Cannot refer to a non-final variable inside an inner class defined in a different method

但是您的解决方案看起来不错.此外,如果 data 是最终的,您可以将代码简化为:

But your solution looks fine. In addition, provided that data is final, you could simplify the code to this:

public void OnNewSensorData(final Data data) {
    runOnUiThread(new Runnable() {
        public void run() {
            // use data here
            data.doSomething();
        }
    });
}

这篇关于Android - 如何在runOnUiThread 中将数据传递给Runnable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆