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

让人想犯罪 __ 提交于 2019-12-03 08:51:08

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.");
      }
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!