在安卓系统中控制下载管理器的下载顺序

9

以下是需要翻译的内容:

我有一个如下的使用场景:

需要下载多个文件,例如 A B C D E F。

在开始下载时,如果 A B 下载完成,而 C 正在下载,我想要中断 C 的下载并开始下载 E。

之后,如果没有其他干扰,继续下载 C D F。

到目前为止,根据我的研究,只有 cancel 方法。

downloadManager.remove(downloadReference); 如何通过 Download manager 实现这个功能?或者还有其他方法吗?谢谢。

    private long startDownload(String url) {
    Uri DownloadUri = Uri.parse(url);       
    String fileName = StorageUtils.getFileNameFromUrl(url);
    String destination = null;

    downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(
            DownloadUri);

    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
    request.setAllowedOverRoaming(false);

    request.setTitle(fileName);
    request.setDescription("com.example.services");

    if (StorageUtils.isSDCardPresent()
            && StorageUtils.isSdCardWrittenable()
            && StorageUtils.checkAvailableStorage()) {
        destination = StorageUtils.SDCARD_ROOT;
    }

    try {
        StorageUtils.mkdir();
    } catch (IOException e) {
        e.printStackTrace();
    }

    request.setDestinationInExternalPublicDir(destination, fileName);
    downloadReference = downloadManager.enqueue(request);

    Log.d("Downloader","Start download manager: " + destination + fileName);
    return downloadReference;
}
1个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
7

关于这个答案,看起来你可以取消下载,然后继续下载剩余的文件。例如:

注册一个BroadcastReceiver,在C完成时通知您:

BroadcastReceiver onComplete = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
    //check if it is B that is complete
    //cancel C
    // download E

    //check if it is E that is complete

// Open connection to URL.
HttpURLConnection connection =
        (HttpURLConnection) url.openConnection();

// Specify what portion of file to download.
connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
// here "downloaded" is the data length already previously downloaded.

// Connect to server.
connection.connect();

    }
 };

registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

//download A
//download B
//download C

谢谢。如何在取消下载管理器任务时保留文件?由于从队列中删除引用 ID 将导致文件被删除。 - user782104
实际上,这段代码只适用于使用I/O流来下载文件的情况,而不是下载管理器。因为下载管理器中没有“暂停”(停止并保存文件)的功能。有没有其他方法解决这个问题?谢谢。 - user782104
我不知道,我需要调查一下。 - hichris123

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