2011-10-05 44 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();