Search code examples
androiddownloaddownload-managerandroid-download-manager

Control the download ordering of Download manager in android


have an use case like the following:

There are several files to download e.g. A B C D E F

When the downloading is started , say the A B is finished and C is downloading, I would like to interrupt the download of C and start the download of E

Then, after E is finished (if there is no other interruption), continue to C D F.

So far form my research there is only cancel method

downloadManager.remove(downloadReference); How to achieve this through Download manager or are there other approach ? thanks

    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;
}

Solution

  • Regarding this answer, it looks like you can cancel the download and then download the rest of the file. For example:

    Register a BrodcastReciever to notify you when C is completed:

    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