我試圖下載多個二進制文件使用包含一個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