我目前正在使用AsyncTask
要在我的应用程序后台下载大文件,当前下载进度显示为ProgressDialog
这是通过更新onProgressUpdate
如下:
protected String doInBackground(String... sUrl) {
try {
String destName = sUrl[1];
file_Delete(destName); // Just to make sure!
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(destName);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e(TAG, NAME + ": Error downloading file! " + e.getMessage());
return e.getMessage();
}
return null;
}
@Override protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
DownloadImage.mProgressDialog.setProgress(progress[0]);
}
这工作正常,但是我现在想在通知栏中使用通知,因此要跟踪下载情况(因为文件可能相当大,并且用户希望从应用程序外部跟踪)。
我已经尝试了下面的代码,但是 UI 开始严重滞后,我可以看到它是由于publishProgress
经常被调用,那么我该如何更改后台代码来调用publishProgress
仅每秒
@Override protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
DownloadImage.mProgressDialog.setProgress(progress[0]);
DownloadImage.myNotification = new NotificationCompat.Builder(c)
.setContentTitle("Downloading SlapOS")
.setContentText("Download is " + progress[0] + "% done")
.setTicker("Downloading...")
.setOngoing(true)
.setWhen(System.currentTimeMillis())
.setProgress(100, progress[0], false)
.setSmallIcon(R.drawable.icon)
.build();
DownloadImage.notificationManager.notify(1, DownloadImage.myNotification);
}
那么我怎样才能改变后台代码以每秒调用一次publishProgress
我之前已经为上传功能做过这个,该功能显示了 %Notification
,但同样的想法。有你的AsyncTask
跟踪什么percentDone
下载的是,并且ONLY call publishProgress
when percentDone
变化。这样,您只需调用publishProgress
当下载的百分比发生变化时,Notification
因此需要更新。这应该可以解决 UI 延迟问题。
我正在将其写为我建议的实现,听起来 OP 已经开始工作了。但也许这会在未来帮助其他人:
byte data[] = new byte[1024];
long total = 0;
int count, latestPercentDone;
int percentDone = -1;
while ((count = input.read(data)) != -1) {
total += count;
latestPercentDone = (int) Math.round(total / fileLength * 100.0);
if (percentDone != latestPercentDone) {
percentDone = latestPercentDone;
publishProgress(percentDone);
}
output.write(data, 0, count);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)