Android依次下载多个文件并在ListView中显示进度

3
用户可以添加任意数量的下载任务,但是下载将一个接一个地开始,即下一个下载将在当前下载完成后才会开始。用户将离开显示下载进度的活动以添加新的下载任务,当添加了新文件进行下载时,应用程序会导航回显示下载进度的活动,在那里它将显示之前添加的下载进度,并将当前添加的文件保留为待处理下载。一旦下载完成,待处理下载将开始下载。
通过这种方式,用户可以添加任意数量的下载任务,它们将一个接一个地开始。我想在后台串行下载它们 - 一个接一个。我希望在ListView中显示进度和状态,所以ListView看起来像:

文件1...正在进行中,39%完成

文件2...待处理

文件3...待处理

文件4...待处理


考虑使用AsyncTask,但不知道如何在当前下载完成后启动下一个挂起的下载的进度条。还有,在用户导航到另一个活动以添加新下载时,如何保持进度条更新。 - user2416657
1个回答

1
我建议使用 IntentServices:
public class FileDownloader extends IntentService {

private static final String TAG = FileDownloader.class.getName();



public FileDownloader() {
    super("FileDownloader");
}

@Override
protected void onHandleIntent(Intent intent) {
    String fileName = intent.getStringExtra("Filename");
    String folderPath = intent.getStringExtra("Path");
    String callBackIntent = intent
            .getStringExtra("CallbackString");

     // Code for downloading

     // When you want to update progress call the sendCallback method

}

private void sendCallback(String CallbackString, String path,
        int progress) {

        Intent i = new Intent(callBackIntent);
        i.putExtra("Filepath", path);
        i.putExtra("Progress", progress);
        sendBroadcast(i);

}

}

然后要开始下载文件,只需执行以下操作:

Intent i = new Intent(context, FileDownloader.class);
i.putExtra("Path", folderpath);
i.putExtra("Filename", filename);
i.putExtra("CallbackString",
            "progress_callback");
startService(i);

现在,您应该像处理任何其他广播一样处理“progress_callback”回调,注册接收器等。在此示例中,使用文件路径确定应更新其进度可视化的文件。
不要忘记在清单中注册服务。
 <service android:name="yourpackage.FileDownloader" />

注意:

使用此解决方案,您可以立即为每个文件启动一个服务,并随意处理每个服务报告的新进度的广播。无需等待每个文件下载完毕后再开始下一个。但如果您坚持按顺序下载文件,当等待100%的进度回调时才调用下一个文件。

使用'CallbackString'

您可以在Activity中像这样使用它:

private BroadcastReceiver receiver;

@Overrride
public void onCreate(Bundle savedInstanceState){

  // your oncreate code

  // starting the download service

  Intent i = new Intent(context, FileDownloader.class);
  i.putExtra("Path", folderpath);
  i.putExtra("Filename", filename);
  i.putExtra("CallbackString",
            "progress_callback");
  startService(i);

  // register a receiver for callbacks 
  IntentFilter filter = new IntentFilter("progress_callback");

  receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      //do something based on the intent's action
      Bundle b = intent.getExtras();
      String filepath = b.getString("Filepath");
      int progress = b.getInt("Progress");
      // could be used to update a progress bar or show info somewhere in the Activity
    }
  }
  registerReceiver(receiver, filter);
}

请在 onDestroy 方法中运行此代码:
@Override
protected void onDestroy() {
  super.onDestroy();
  unregisterReceiver(receiver);
}

请注意,“progress_callback”可以是您选择的任何其他字符串。
示例代码来自以编程方式注册广播接收器

请问您能否提供有关CallbackString的更多信息?它实际上是什么,我应该如何使用它? - 0xh8h
1
温馨提示!IntentService在API 30中已被弃用。 - Khay Leng

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接