Java-无法在后台的while循环中发布异步任务的进度-Android
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java-无法在后台的while循环中发布异步任务的进度-Android,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2161字,纯文字阅读大概需要4分钟。
内容图文
![Java-无法在后台的while循环中发布异步任务的进度-Android](/upload/InfoBanner/zyjiaocheng/691/63fc3d0115e549ef9f9ba857a39ca55b.jpg)
我想从doInBackground更新对话框的下载进度.
我正在打印日志以及发布进度.
他们俩都没有工作.
最后更新对话框,并一次打印所有日志值
private class DownloadEReport extends AsyncTask<String, Void, Void> {
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();
}
内容总结
以上是互联网集市为您收集整理的Java-无法在后台的while循环中发布异步任务的进度-Android全部内容,希望文章能够帮你解决Java-无法在后台的while循环中发布异步任务的进度-Android所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。