【发布时间】:2010-06-12 17:38:04
【问题描述】:
我想将数据从Thread 传回Activity(创建线程)。
所以我按照Android documentation 中的描述进行操作:
public class MyActivity extends Activity {
[ . . . ]
// Need handler for callbacks to the UI thread
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
updateResultsInUi();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
[ . . . ]
}
protected void startLongRunningOperation() {
// Fire off a thread to do some work that we shouldn't do directly in the UI thread
Thread t = new Thread() {
public void run() {
mResults = doSomethingExpensive();
mHandler.post(mUpdateResults);
}
};
t.start();
}
private void updateResultsInUi() {
// Back in the UI thread -- update our UI elements based on the data in mResults
[ . . . ]
}
}
我在这里只缺少一件事 - 应该在哪里以及如何定义 mResults 以便我可以从 Activity 和 Thread 访问它,并且还可以根据需要进行修改?如果我在MyActivity 中将其定义为final,我将无法再在Thread 中更改它 - 如示例所示...
谢谢!
【问题讨论】:
标签: android multithreading communication android-activity