我正在尝试使用包含用于执行后台工作的AsynTask的服务来下载多个二进制文件。我能够成功运行服务,我已在Manifest文件中注册它。我可以下载文件,但是我想在通知栏中显示进度条。我在onPreExecute()方法中创建Notification栏并设置progressbar并在onProgressUpdate()方法中通知NotifactionManager。
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私有类位于DownloadService类中,该类扩展了Service。我无法显示或更新通知栏。
我目前在线上收到IllegalArgumentException: notificationManager.notify(NOTIFICATION_ID,通知);
真的很感谢你对这个的帮助!
编辑:NOTIFICATION_ID定义如下:private int NOTIFICATION_ID = R.string.app_name
答案 0 :(得分:0)
可能迟到回答这个问题,但我目前正在编写一个具有类似代码的应用程序。
NOTIFICATION_ID必须是int类型,因为notify()的第一个参数接受int而不是代码中的字符串。
以下是有关通知及其不同签名的更多信息:
答案 1 :(得分:0)
我认为您需要将通知添加到通知管理器。我不确定。我试着让我知道。这是我的代码:
notificationManager = (NotificationManager) getApplicationContext().getSystemService(
getApplicationContext().NOTIFICATION_SERVICE);
notificationManager.notify(10, notification);
// simulate progress
Thread download = new Thread() {
@Override
public void run() {
for (int i = 1; i < 100; i++) {
progress++;
notification.contentView.setProgressBar(R.id.status_progress, 100, progress, false);
// inform the progress bar of updates in progress
notificationManager.notify(id, notification);
try {
Thread.sleep(125);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
download.run();