2013-02-27 70 views
1

ActivityonCreate裏面我做了以下內容:Android的:從一個的AsyncTask的返回值,而不會阻塞UI線程

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState);   
    AsyncTask<String, Integer, String[]> asynctask = new DownloadFilesTask(this.getActivity()).execute(url); 
    String[] values = null;   
    try { 
     values = asynctask.get(); 
    } catch (InterruptedException e) {   
     e.printStackTrace(); 
    } catch (ExecutionException e) { 
     e.printStackTrace(); 
    } 
    Log.d("AsyncTask", "DONE!");   
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), 
      android.R.layout.simple_list_item_1, values); 

    setListAdapter(adapter); 
} 

這工作,但我阻止與asynctask.get(); UI線程它阻止我從在執行後臺任務期間顯示任何新的UI元素,例如對話框。

所以我的問題:我如何從我的AsyncTask獲取結果值而不會阻止給出此代碼的UI線程?

回答

5

移動這onPostExecute

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), 
     android.R.layout.simple_list_item_1, values); 

setListAdapter(adapter); 
+0

你有最直接的答案。它現在有用,謝謝! – 2013-02-27 19:58:37

+0

使用AsyncTasks時,請務必說明用戶導航離開的情況,並且在調用postExecute時UI已經死亡。 – Krylez 2013-02-27 20:32:03

1

get()被設計爲從內onPostExecute(Result result)調用。基本上後者是在doInBackground()完成或引發異常之後在UI線程上執行的。

例如:

class DownloadFilesTask extends AsyncTask<Params, Progress, Result> 
{ 
    @Override 
    public Result doInBackground(Params... params) 
    { 
     // ... 
    } 

    @Override 
    public void onPostExecute(Result result) 
    { 
     try 
     { 
      Result result = get(); 

      // we are fine here, do something with the result 
     } 
     catch(CancellationException e){/* if cancel() is called on this instance */} 
     catch(ExecutionException e){/* if doInBackground() throws some exception */} 
     catch(InterruptedException e){/* If the current thread was interrupted while waiting */} 
    } 
} 


編輯:我必須SwingWorker混淆:\

doInBackground()結束後,onPostExecute(Result result)在UI線程上執行結果從傳遞210作爲方法參數。

class DownloadFilesTask extends AsyncTask<Params, Progress, Result> 
{ 
    @Override 
    public Result doInBackground(Params... params) 
    { 
     // ... 
    } 

    @Override 
    public void onPostExecute(Result result) 
    { 
     // do something with the result 
    } 
} 
+0

其實不,它不是,因爲在onPostExecute你有結果(驚喜! )結果變量... get()用於強制不是異步行爲... – Selvin 2013-02-27 19:54:37

+0

@Selvin你是什麼意思?你能詳細解釋一下嗎? – 2013-02-27 19:57:19

+0

onPostExecute(Result result)...結果result = get(); ... – Selvin 2013-02-27 19:58:50

0

1 - 你能不能也發佈DownloadFilesTask?

2-當asyncTask執行時,它不會被加載,或者你在做什麼,這不會馬上發生,對吧?所以,只要你打電話給asynctask你可能無法得到它的結果...所以我建議你使用asyncTask的onPostExecute方法

相關問題