简体   繁体   中英

How to stop a running download after a system reboot

Here is the situation:

  1. I start a download
  2. I restart the device (to test the robustness of the app)
  3. I use a boot receiver to be notified of the restart
  4. In the onReceive method I call the clearDownloadsAfterReboot() method:

      @Override public void onReceive(final Context context, Intent intent) { clearDownloadsAfterReboot(context); } 
  5. The clearDownloadsAfterReboot() method get called and tries to remove the downloads like so:

     private void clearDownloadsAfterReboot(final Context context){ //Added delay to make sure download has started new Handler().postDelayed(new Runnable() { @Override public void run() { DownloadManager manager = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE); DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById (DownloadManager.STATUS_FAILED|DownloadManager.STATUS_PENDING|DownloadManager.STATUS_RUNNING|DownloadManager.STATUS_PAUSED); Cursor c = manager.query(query); // -------> c.getCount() returns 0 despite the download being visible while(c.moveToNext()) { //This never executes because c has a count of 0 int removedInt = manager.remove(c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID))); } } }, 45000); } 
  6. The cursor returns 0 so the remove() method is never called, but, I can see the download running in the status bar so there is at least 1 download running.

My questions in a nutshell: How do I stop running downloads after a reboot? And, why would the manager.query() method return a cursor which has 0 results when there is a download running?

I know there are other question regarding stopping downloads but these have not been able to solve my issue.

Thanks in advance.

Credit for the first part of this answer goes to @Lukesprog

I needed to use setFilterByStatus() instead of setFilterById() . After exchanging these two methods I was able to successfully stop the download and the manager.query() method returned a cursor containing the correct amount of downloads.

However, for some reason the notification which showed the progress of the download didn't clear after the download had been stopped. In order to clear the notification you need to call manager.remove(c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID))); twice .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM