2010-06-12 47 views
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,所以我可以從兩個ActivityThread訪問它,也將是能夠根據需要進行修改?如果我在MyActivity中將其定義爲final,則不能再在Thread中更改它 - 如示例中所示...

謝謝!

回答

2

如果您在類中定義了mResults而不是方法,則可以從任一位置對其進行更改。例如:

protected Object mResults = null; 

(使用受保護的,因爲it's faster

+2

Android的性能文檔表明包的範圍,不受保護。受保護的可以將實現細節泄漏到包之外的子類。 – adamp 2010-06-12 20:11:53

+0

這應該是'揮發性'的工作。 – Gray 2013-03-26 16:14:46

相關問題