show ProgressBar or Dialog from an IntentService for download progress

8.9k views Asked by At

I have an activity with a "download" button which fires up DownloadManager implemented in an IntentService. Everything is working just fine and my question is:

Is it possible to display ProgressBar or ProgressDialog from my DownloadService (which is extended IntentService), except the progress shown in the Notification bar?

Could you write a sample code or pseudo code how I can do that? Thank you

1

There are 1 answers

11
Simon Dorociak On BEST ANSWER

Is it possible to display ProgressBar or ProgressDialog from my DownloadService (which is extended IntentService), except the progress shown in the Notification bar?

Could you write a sample code or pseudo code how I can do that? Thank you

You can use ResultReceiver to reach your goal. ResultReceiver implements Parcelable so you are able to pass it into IntentService like:

Intent i = new Intent(this, DownloadService.class);
i.putExtra("receiver", new DownReceiver(new Handler()));
<context>.startService(i);

Then in your onHandlerIntent() all what you need is to obtain receiver you passed into Intent and send current progress into ResultReceiver:

protected void onHandleIntent(Intent intent) {  

   // obtaining ResultReceiver from Intent that started this IntentService
   ResultReceiver receiver = intent.getParcelableExtra("receiver");

   ...

   // data that will be send into ResultReceiver
   Bundle data = new Bundle();
   data.putInt("progress", progress);

   // here you are sending progress into ResultReceiver located in your Activity
   receiver.send(Const.NEW_PROGRESS, data);
}

And ResultReceiver will handle data and will make update in ProgressDialog. Here is implementation of ResultReceiver (make it as inner class of your Activity class):

private class DownReceiver extends ResultReceiver {

   public DownloadReceiver(Handler handler) {
      super(handler);
   }

   @Override
   public void onReceiveResult(int resultCode, Bundle resultData) {
      super.onReceiveResult(resultCode, resultData);
      if (resultCode == Const.NEW_PROGRESS) {
         int progress = resultData.getInt("progress");

         // pd variable represents your ProgressDialog
         pd.setProgress(progress);
         pd.setMessage(String.valueOf(progress) + "% downloaded sucessfully.");
      }
   }
}