我目前正在使用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);
}