AsyncTask在后台运行时看不到ProgressDialog

我在我的应用程序中使用AsyncTask下载URL。 我在onPreExecute()上使用ProgressDialog进行等待。 但是我在进程结束时看不到ProgressDialog,我看了一会儿。 想要在下载之后看到它。 谁能帮我。 谢谢我的代码是这样的:

private class loadMoreListView extends AsyncTask { @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(); } } 

首先注意附加到所有AsyncTask Implemented方法的“@override”标头,例如

 private class loadMoreListView extends AsyncTask { 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(); } } 

除非您必须在UI上执行某些操作,否则还要从doInBackground中删除它。

 runOnUiThread(new Runnable() { public void run() { // do something for downloading } }); 

您无法在runOnUiThread上执行下载操作。 doInBackground用于运行UI等不可见的下载等后台任务。

  runOnUiThread(new Runnable() { public void run() { // do something for downloading } 

//在runOnUiThread中执行下载操作是错误的。 runOnUiThread在UI线程上运行“执行下载操作”,并且您的应用程序应该因NetworkOnMainThreadException而崩溃,您的应用程序在设备上运行的版本比GingerBread的android更重要。 不同的是它会阻止ui线程阻止他绘制你的进度条

问题在于

runOnUiThread(new Runnable(){

  public void run() { // do something for downloading } }); 

如果UI线程仍然忙,ProgressDialog将不会更新。 SO中有很多例子。 我不明白为什么你需要UIthread。 并且根据经验 – 如果你需要进度对话框,你需要让它在后台线程中运行asynctask,就像它一直做的那样。阅读文档

http://developer.android.com/reference/android/os/AsyncTask.html

您可以使用以下示例

http://www.androidhive.info/2012/01/android-json-parsing-tutorial/