Possible Duplicate:
AsyncTask block UI threat and show progressbar with delay
我想在从任何服务器检索 JSON 时显示一个 progressDialog。所以我使用 AsyncTask 作为解决方案(不确定有什么不同的出路)。
一切都很好,ProgressDialog 可以正常工作,直到我使用 AsyncTask 实例调用 .get() 方法。我想它以某种方式阻止了用户界面。这是我的 AsyncTask:
public class myAsync extends AsyncTask<String, String, List> {
String message; // for dialog message
ProgressDialog progress;
Intent myIntent;
Context ctx;
public myAsync(String message, Context ctx) {
this.message = message;
this.ctx = ctx;
progress = new ProgressDialog(ctx);
}
@Override
protected void onPreExecute() {
progress.setMessage(message);
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.show();
}
@Override
protected List doInBackground(String... params) {
//returns any list after the task
return anyList;
}
@Override
protected void onPostExecute(List result) {
if(progress.isShowing())
progress.dismiss();
}
}
这是调用 AsyncTask 的 myActivity:
myAsync asyncTask = new myAsync("Loading...", this);
asyncTask.execute("Any string", "Other string");
asyncTask.get(); // If I comment out this line, ProgressDialog works
执行后,当我尝试从 doInBackground 和 onPostExecute 记录结果时,都没有问题。但是如果我想用 .get() 得到结果 ProgressDialog 没有显示或显示时间太短(可能是 0.2 秒)
有什么问题?
最佳答案
是的,get()
等待 必要时计算完成,然后检索其结果。这意味着,您正在阻塞您的 UI 线程,等待结果。
解决方法:不要调用get
通常,你会在postExecute
中调用一个函数(回调)。
关于android - 调用 AsyncTask.get() 时未显示 ProgressDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9019249/