我在这个应用程序中有一个 Asynctask,我在 onPreExecute 中有一个 ProgressDialog。
ProgressDialog pDialog;
protected void onPreExecute() {
pDialog = new ProgressDialog(Synchronization.this);
pDialog.setMessage(Html.fromHtml("<b>Please Wait</b><br/>Working..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
并且,在 onPostExecute 中,我关闭了这个对话框。
protected void onPostExecute(ArrayList<Object> allShopsData) {
// TODO Auto-generated method stub
super.onPostExecute(allShopsData);
final ArrayList<Object> allShops = allShopsData;
// dismiss the dialog after getting all products
if(pDialog!=null && pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
ExpandableListView expandableList = (ExpandableListView) findViewById(R.id.expandlist);
expandableList.setDividerHeight(2);
expandableList.setGroupIndicator(null);
expandableList.setClickable(true);
MyExpandableAdapter adapter = new MyExpandableAdapter(taskList,
allShops);
adapter.setInflater(
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE),
Synchronization.ref);
expandableList.setAdapter(adapter);
}
});
}
我在同步(我的主要 Activity )onCreate() 中启动名为“task1”的 Asynctask。 现在,我在 MainActivity 中有一个菜单,我在其中取消了“task1”引用的 Asynctask,并创建了另一个 Asynctask 实例,将其分配给“task1”。
task1.cancel(true);
task1 = new GetShopsTask();
task1.execute(taskList);
但在这里,我看到创建的一个进度对话框在 onPostExecute 之后关闭(我还可以看到我的 View 在后台更新)但紧接着,另一个进度对话框弹出,但没有被关闭。 不确定,是什么部分造成的。有人可以帮忙吗?
最佳答案
问题是当您取消 AsyncTask 时,不会调用 onPostExecute 而是调用 onCanceled()。请参阅 AsyncTask 源代码。
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
因此您的进度对话框不会关闭,因为永远不会调用 onPostExecute。您可以通过将此添加到异步任务来解决问题:
@Override
protected void onCancelled()
{
// dismiss the dialog on canceled task
if(pDialog!=null && pDialog.isShowing())
pDialog.dismiss();
}
关于android - ProgressDialog 不会因多个 Asynctask 实例而关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20556140/