这个问题已经在这里有了答案:
9年前关闭。
我想在从任何服务器检索JSON时显示一个progressDialog。因此,我已经使用AsyncTask作为解决方案(不确定任何其他出路)。
一切都很好,ProgressDialog可以正常工作,直到我使用AsyncTask实例调用.get()方法为止。我想它以某种方式阻止了UI。这是我的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();
}
}
这是myActivity,称为AsyncTask:
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
中调用一个函数(回调)。