AsyncTask 在后台运行时看不到 ProgressDialog [英] Can't see ProgressDialog while AsyncTask run in background
问题描述
我在我的应用程序中使用 AsyncTask 来下载一个 url.我在 onPreExecute() 上使用 ProgressDialog 进行等待.但是我在进程完成时看不到 ProgressDialog,我看到了一会儿.想在下载时看到它而不是在那之后.谁能帮我.谢谢我的代码是这样的:
I use AsyncTask in my App for download a url. I use a ProgressDialog on onPreExecute() for waiting. But I cant see ProgressDialog while process finish and i see it for a moment. want to see it while downloading not after that. can any one help me. thanks my code is like this:
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(SingleMenuItemActivity.this);
pDialog.setMessage("Please Wait ...");
pDialog.isIndeterminate();
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... unused) {
runOnUiThread(new Runnable() {
public void run() {
// do something for downloading
}
});
return (null);
}
protected void onPostExecute(Void unused) {
// closing progress dialog
pDialog.dismiss();
}
}
推荐答案
首先注意@override"标题附加到所有 AsyncTask 实现的方法,例如
Firstly notice the "@override" header attached to all the AsyncTask Implemented methods e.g.
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
ProgressDialog pDialog;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(SingleMenuItemActivity.this);
pDialog.setMessage("Please Wait ...");
pDialog.isIndeterminate();
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pDialog.cancel();
}
}
同时从 doInBackground 中删除它,除非你必须在 UI 上做一些事情.
Also Remove this from doInBackground unless you must do something on the UI.
runOnUiThread(new Runnable() {
public void run() {
// do something for downloading
}
});
您无法在 runOnUiThread 上执行下载操作.doInBackground 用于运行 UI 不可见的后台任务,如下载等.
You cannot do something for downloading on the runOnUiThread. doInBackground is meant for running background tasks like downloads etc. not visible to the UI.
这篇关于AsyncTask 在后台运行时看不到 ProgressDialog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!