2
我想將數據從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的性能文檔表明包的範圍,不受保護。受保護的可以將實現細節泄漏到包之外的子類。 – adamp 2010-06-12 20:11:53
這應該是'揮發性'的工作。 – Gray 2013-03-26 16:14:46