使用服务中的 AsyncTask 更新通知栏中的进度条?

byt*_*uit 5 android

我正在尝试使用包含用于执行后台工作的 AsynTask 的服务下载多个二进制文件。我能够成功运行服务,我已经在清单文件中注册了它。我可以下载文件,但是我想在通知栏中显示一个进度条。我正在 onPreExecute() 方法内创建通知栏并设置进度条并在 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();
           }
       }
Run Code Online (Sandbox Code Playgroud)

DownloadFileAsync 私有类位于扩展服务的 DownloadService 类中。我无法显示或更新通知栏。

我目前在线上收到一个 IllegalArgumentException:notificationManager.notify(NOTIFICATION_ID, notification);

非常感谢您对此的帮助!

编辑:NOTIFICATION_ID 定义如下:private int NOTIFICATION_ID = R.string.app_name

Kal*_*mah 0

回答这个问题可能已经晚了,但我目前正在编写一个具有类似代码的应用程序。

NOTIFICATION_ID 必须是 int 类型,因为 notification() 的第一个参数采用 int 而不是代码中的字符串。

以下是有关通知及其不同签名的更多信息:

http://developer.android.com/reference/android/app/NotificationManager.html#notify(int,android.app.Notification )