无法在后台的while循环中发布异步任务的进度 – Android

我想从doInBackground更新对话框的下载进度。
我正在打印日志以及发布进度。
他们都没有工作。

它最后更新对话框,最后一次打印所有日志值

private class DownloadEReport extends AsyncTask { int progress = 0; protected void onPreExecute() { mProgressDialog = new ProgressDialog(EReport.this); mProgressDialog.setTitle("Downloads"); mProgressDialog.setMessage("Downloading, Please Wait!"); mProgressDialog.setIndeterminate(false); mProgressDialog.setMax(100); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setCancelable(false); mProgressDialog.show(); } @Override protected void onProgressUpdate(Void... values) { super.onProgressUpdate(values); mProgressDialog.setProgress(progress); } @Override protected Void doInBackground(String... strings) { String mUrl = strings[0]; String json = ""; int count; try { URL url = new URL(mUrl); URLConnection conection = url.openConnection(); conection.connect(); // getting file length int lenghtOfFile = conection.getContentLength(); // input stream to read file - with 8k buffer InputStream input = new BufferedInputStream(url.openStream(), 8192); // Output stream to write file OutputStream output = new FileOutputStream("/sdcard/downloadedfile.txt"); byte data[] = new byte[1024]; long total = 0; while ((count = input.read(data)) != -1) { total += count; // writing data to file output.write(data, 0, count); // publishing the progress.... // After this onProgressUpdate will be called Log.e("JSON Download Progress", "" + (int) ((total * 100) / lenghtOfFile)); progress = (int) (total * 100 / lenghtOfFile); publishProgress(); } // flushing output output.flush(); // closing streams output.close(); input.close(); } catch (Exception e) { Log.e("Error: ", e.getMessage()); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); mProgressDialog.dismiss(); } } 

从onProgressUpdate中删除super,然后尝试

 @Override protected void onProgressUpdate(Void... values) { //super.onProgressUpdate(values); mProgressDialog.setProgress(progress); } 

如果它不能在你的循环中添加一个sleep语句,那么这个循环将释放处理器并给出时间来发布进度

 try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } 

对该行为的一种可能解释是从远程输入流读取并将其写入输出缓冲区非常快。 我尝试了相同的代码但只运行了10次循环。

 int total = 0; while(total <= 100){ progress = total; total += 10; publishProgress(); } 

即使我最初看不到进度对话框,所以在循环中放入一个Thread.sleep()并且进度对话框工作正常。

 int total = 0; while(total <= 100){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } progress = total; total += 10; publishProgress(); } 

尝试将您正在写入输出缓冲区的时间( System.currentTimeMillis() )记录下来。

希望能帮助到你。