Android的 - HOWTO传递runOnUiThread数据到可运行? [英] Android - howto pass data to the Runnable in runOnUiThread?

查看:295
本文介绍了Android的 - HOWTO传递runOnUiThread数据到可运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更新一些UI,做它的UI线程内使用 runOnUiThread
现在的UI数据来自这里由数据psented其他线程,再$ P $

如何将数据传递到运行的,所以谓它们可以被用来更新UI? 安卓似乎并没有允许直接使用数据。有一种优雅的方式来做到这一点?

 公共无效OnNewSensorData(数据数据){

    runOnUiThread(新的Runnable(){
        公共无效的run(){
            //使用的数据
        }
    });
}
 

我的解决办法是建立一个fioeld 私有数据sensordata 可运行的内,和分配数据给它。只是这工作,如果原来的数据数据是最终的。

 公共无效OnNewSensorData(最终数据的数据){

    runOnUiThread(新的Runnable(){
        私人数据sensordata =数据;
        公共无效的run(){
            //使用sensordata其等于数据
        }
    });
}
 

解决方案

您发现的问题是,

  

内部类在Java中捕获(关闭了)词汇范围中   它们被定义。但他们只捕获被宣布最终的变量。

如果这是明确的泥,还有这里的细节了很好的讨论: <一href="http://stackoverflow.com/questions/1299837/cannot-refer-to-a-non-final-variable-inside-an-inner-class-defined-in-a-different">Cannot指非final的变量在不同的方法定义的内部类里面

但您的解决方案看起来很好。此外,只要数据是最后一个,你可以简化code到这一点:

 公共无效OnNewSensorData(最终数据的数据){
    runOnUiThread(新的Runnable(){
        公共无效的run(){
            //此处使用的数据
            data.doSomething();
        }
    });
}
 

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.

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
        }
    });
}

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
        }
    });
}

解决方案

The problem you found is that

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

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的 - HOWTO传递runOnUiThread数据到可运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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