Search code examples
javaandroidtask-queueandroid-download-manager

Android - DownloadManager - Clear old downloads in queue


I'm building an app which needs to know for concurrency reasons if all downloads are finished. A certain function is only allowed to start when all my downloads are finished.

I managed to write a function which checks the queue for old downloads:

DownloadManager dm = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);

    Query q = new Query();
    q.setFilterByStatus(DownloadManager.STATUS_FAILED|DownloadManager.STATUS_PENDING|DownloadManager.STATUS_RUNNING);

    Cursor c = dm.query(q);

The problem is that - just to be sure - at initialization I want to clean up the queue and remove all entries.

Any ideas how I can now remove the entries?

This function didn't work for me because I don't want to physically delete the files...just empty the queue.

Any ideas?


Solution

  • Can you wait for the DownloadManager to finish only your own downloads? To achieve this, you can save handles of your downloads with something like this:

    List<Long> downloadIds = new ArrayList<>();
    downloadIds.add(downloadManager.enqueue(request));
    

    Then you can query the downloadManager this way:

        Query q = new Query();
        long[] ids = new long[downloadIds.size()];
        int i = 0;
        for (Long id: downloadIds) ids[i++] = id;
        q.setFilterById(ids);
        Cursor c = downloadManager.query(q);
        Set<Long> res = new HashSet<>();
        int columnStatus = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
        while (c.moveToNext()) {
            int status = c.getInt(columnStatus);
            if (status != DownloadManager.STATUS_FAILED && status != DownloadManager.STATUS_SUCCESSFUL) {
                // There is at least one download in progress
            }
        }
        c.close();
    

    Bear in mind that this can work if you're interested only in your own downloads, not every possible download that can occur system wide.

    Hope this helps.