我有以下代码:
try {
res = new Utils(ubc_context).new DownloadCalendarTask().execute().get();
} catch (InterruptedException e) {
Log.v("downloadcalendar", "interruptedexecution : " + e.getLocalizedMessage());
res = false;
} catch (ExecutionException e) {
Log.v("downloadcalendar", "executionexception : " + e.getLocalizedMessage());
res = false;
}
Log.v("displaymenu", "A");
public class Utils {
private Context context;
public Utils(Context context) {
this.context = context;
}
public class DownloadCalendarTask extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog dialog;
public DownloadCalendarTask() {
dialog = new ProgressDialog(context);
}
protected void onPreExecute() {
Log.v("preexecute", "A");
dialog.setMessage("Loading calendar, please wait...");
Log.v("preexecute", "B");
dialog.show();
Log.v("preexecute", "C");
}
protected Boolean doInBackground(Void... arg0) {
// do some work here...
return (Boolean) false;
}
protected void onPostExecute() {
Log.d("utils", "entered onpostexecute");
dialog.dismiss();
}
}
}
代码的第一部分附加到onClick
侦听器以获取按钮。当我单击按钮时按钮闪烁(因为它显示它已被点击),然后大约8秒后出现加载对话框但从未完成。
根据logcat,我单击按钮onPreExecute
按Dialog.show()
执行,所以我的第一个问题是为什么会有8秒延迟?在这8秒内,logcat显示正在执行doInBackground
。但是,根据logcat(这是第二个问题)onPostExecute永远不会被调用(因此Dialog.dismiss())永远不会运行。
Logcat显示正在执行DownloadCalendarTask().execute().get()
之后的所有内容,因此就好像刚刚跳过onPostExecute
一样。
非常感谢你的帮助!
答案 0 :(得分:1)
您正在调用AsyncTask.get(),这会导致在执行AsyncTask时阻止UI线程。
new DownloadCalendarTask().execute().get();
如果删除对get()的调用,它将异步执行并给出预期的结果。
new DownloadCalendarTask().execute();
编辑: 您还需要将参数更新为onPostExecute方法,它们需要包含结果。 e.g。
protected void onPostExecute(Boolean result) {