2011-10-05 31 views
4

我试图下载多个二进制文件使用包含一个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

回答

0

我想你需要到您的通知添加到通知manager.Iam不知道it.U尝试,让我know.Here是我的代码:

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();