2015-02-06 127 views
-1

我只是有一個公共職能,我有一些循環等,並在我的函數開始我開始我的AsyncTask它返回一個值,這是在該函數的結尾附近需要的值。但不知何故,AsyncTask在這個函數完成後纔會啓動?有沒有辦法在之前或平行運行Asynctask?直到今天,我認爲AsyncTask通常並行運行。我發現了方法AsyncTask在函數完成後啓動

獲得()

但這凍結線程...我需要一種替代或修復

public void my_function() 
    { 
     new async_task().execute() 
     ... //do something 

     if (returned_value_from_async_task == 10) //Here I need the variable which is returned in the async_task 
     { 
     ... //do something 
     } 

    } //End of function 

//When I go to debug mode the AsyncTask starts right here 

回答

2

是。這就是AsyncTask的「異步」部分。函數結尾的代碼不會等待任務完成。所以你不能依靠那些數據在那裏。您在函數中運行的代碼可能需要的時間比使用ThreadPoolExecutor後臺時間更短。

執行,在onPostExecute

編輯取決於從AsyncTask數據的代碼:
不知道什麼是「更復雜」的意思,這是很難說你最好的選擇是什麼。但是,你可能分裂的功能,正是如此

public void preExecutePrep() { 
    YourTask yourTask = new YourTask(); 
    yourTask.execute(); 

    //do what you can without the result 
} 

private void postExecuteCode(int result) { 
    if (result != 10) return; 
    //do the rest 
} 

然後調用postExecuteCodeonPostExecute。如果這不會削減它,我需要更多的具體信息來幫助

+0

功能比這更復雜。所以我不能把它放在'onPostExecute'。是不是有另一種方式? – 2015-02-06 18:29:46

+0

好的,這實際上是一個很好的提示。我會試一試!謝謝 – 2015-02-06 18:55:09

相關問題