[英]Android: Get the return value from an AsyncTask without blocking the UI thread
在Activity
的onCreate
內,我執行以下操作:
@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();
但是我用asynctask.get();
阻止了UI線程asynctask.get();
這使我無法在執行后台任務時顯示任何新的UI元素(如對話框)。
所以我的問題是:如何從我的AsyncTask獲取結果值而不給定此代碼,而不會阻塞UI線程?
將其移動到onPostExecute
:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
get()
設計為從
onPostExecute(Result result)
內部
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()
完成之后,在UI線程上執行onPostExecute(Result result)
,並將結果從doInBackground()
傳遞為方法參數。
class DownloadFilesTask extends AsyncTask<Params, Progress, Result> { @Override public Result doInBackground(Params... params) { // ... } @Override public void onPostExecute(Result result) { // do something with the result } }
1-您還可以發布DownloadFilesTask嗎?
2-當asyncTask執行時,它不會被加載或您正在執行的操作,那不會立即發生,對嗎? 因此,僅在調用asynctask之后,您可能無法從中獲取結果...因此,我建議您使用asyncTask的onPostExecute方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.