android - 从 IntentService 显示 ProgressBar 或 Dialog 以获取下载进度

标签 android progress-bar progressdialog download-manager

<分区>

我有一个带有“下载”按钮的 Activity ,它会启动在 IntentService 中实现的 DownloadManager。一切正常,我的问题是:

是否可以从我的 DownloadService(扩展的 IntentService)中显示 ProgressBar 或 ProgressDialog,但通知栏中显示的进度除外?

你能写一个示例代码或伪代码吗?谢谢

最佳答案

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

您可以使用 ResultReceiver 来达到您的目标。 ResultReceiver 实现了 Parcelable,因此您可以像这样将其传递到 IntentService 中:

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

然后在您的 onHandlerIntent() 中,您需要做的就是获取您传递给 Intent 的接收器,并将当前进度发送给 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);
}

ResultReceiver 将处理数据并在 ProgressDialog 中进行更新。这是 ResultReceiver 的实现(将其作为 Activity 类的内部类):

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.");
      }
   }
}

关于android - 从 IntentService 显示 ProgressBar 或 Dialog 以获取下载进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20266178/

相关文章:

android - 仅在 Android Oreo 中显示圆形箭头的进度对话框

android - 具有某些后台逻辑的 Android 中的进度对话框会出现处理程序错误?

android - android中的搜索引擎程序

android - 通过标签管理器在 Google Analytics v4 中的完整堆栈跟踪

android - 将刷新的 ImageView 变成 ProgressBar

android:WAITING连接时显示进度对话框

Android 3.0 WebView 崩溃

android - 需要 Gradle 版本 1.10。当前版本是 2.0

c# - 如何将后台代码的进度百分比传递给Jquery进度条?

android - 白色背景上的进度条