我想将数据从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
访问它,并且还可以根据需要进行修改?如果我在final
中将其定义为MyActivity
,我无法在Thread
中更改它 - 正如示例中所示...
谢谢!
答案 0 :(得分:2)