2013-02-02 32 views
0

我有2 AsyncTask,AsyncOneAsyncTwo。 在第一的AsyncTask後臺方法我得到一個字符串值,並設定在onpostexecute將字符串值從一個異步任務傳遞到另一個

這樣item = i.getname();

這裏item是一個全局變量。

現在我正在設置這個項目的值是onpostexecute AsyncTwo的方法,但我得到空嗎?

如何獲取物品價值?

回答

0

你必須確保的AsyncTask 1結束後,當您啓動異步任務2.你可以把項目作爲的AsyncTask 1場,比可撥打publishProgress時,你可以設置的值,並在任務1的onProgressUpdate開始的AsyncTask 2 。

1

你在做什麼是正確的與你的代碼和全局變量的東西,只要確保你的兩個asyncTask不應該同時在運行模式。開始第二個任務在第一個postExecute()。

0

從你的描述聽起來你有在後臺運行兩個併發任務,TASK2取決於TASK1結果。由於他們是同時運行,TASK2可以完成TASK1不前,所以沒有保證,當TASK2完成,它會得到TASK1結果。

爲了確保您可以同時運行兩個任務,你可以同步的TASK1doInBackround()方法,並提供在TASK1同步getItem()方法:

// in task1 
private Object item; // instance variable to be set in doInBackground 
protected synchronized Object doInBackground(Object... objects) { 
    // set item to some value here 
    item = ...; 
} 
public synchronized Object getItem() { 
    return item; 
} 


// in task2 
protected Object doInBackground(Object... objects) { 
    // do work of task2 
    .... 

    // when finishing our work, ready to get the result of task1. 
    // we don't call task1.getItem() in onPostExecute() to avoid possibly blocking the UI thread 
    Object item = task1.getItem(); 
    // pass item to the onPostExecute method 
} 

與上面的代碼,TASK2將等待任務1完成並得到結果,如果它運行速度比任務1更快。

相關問題