Android - howto pass data to the Runnable in runOnUiThread?(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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Android - 如何在runOnUiThread 中将数据传递给Runnable?
基础教程推荐
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
