Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

show ProgressBar or Dialog from an IntentService for download progress [closed]

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

like image 714
venta7 Avatar asked Nov 28 '22 15:11

venta7


1 Answers

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.");
      }
   }
}
like image 96
Simon Dorociak Avatar answered Dec 04 '22 13:12

Simon Dorociak