我试图下载多个二进制文件使用包含一个AsynTask做后台工作的服务。我能够成功运行服务,我已将其注册到Manifest文件中。我可以下载这些文件,但是我想在通知栏中显示一个进度条。我在onPreExecute()方法内部创建通知栏,并设置进度条并在onProgressUpdate()方法内通知NotifactionManager。在服务中使用AsyncTask更新通知栏中的进度条?
private class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.icon, "Downloading...", System.currentTimeMillis());
contentView = new RemoteViews(getPackageName(), R.layout.progress_layout);
contentView.setProgressBar(R.id.status_progress, 10, 0, false);
contentView.setTextViewText(R.id.status_text,currentFile);
notification.contentView = contentView;
// Toast.makeText(DownloadService.this, "Downloading...!",Toast.LENGTH_SHORT).show();
}
@Override
protected String doInBackground(String... aurl) {
int count;
try {
//Downloading code goes here
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
notification.contentView.setProgressBar(R.id.status_progress, 100, Integer.parseInt(progress[0]), false);
// inform the progress bar of updates in progress
notificationManager.notify(NOTIFICATION_ID, notification);
}
@Override
protected void onPostExecute(String unused) {
Toast.makeText(DownloadService.this, "Download complete!",Toast.LENGTH_SHORT).show();
}
}
DownloadFileAsync私有类位于扩展Service的DownloadService类中。我无法显示或更新通知栏。
我现在正在收到一行IllegalArgumentException: notificationManager.notify(NOTIFICATION_ID,notification);
真的很感谢你的帮助!
编辑:NOTIFICATION_ID定义如下:私人INT NOTIFICATION_ID = R.string.app_name