情况如下:
- 我开始下载
- 我重新启动设备(以测试应用的稳健性)
- 我使用启动接收器来接收重启通知
在 onReceive 方法中,我调用clearDownloadsAfterReboot() 方法:
@Override public void onReceive(final Context context, Intent intent) { clearDownloadsAfterReboot(context); }
clearDownloadsAfterReboot() 方法被调用并尝试删除下载,如下所示:
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); }
光标返回 0,因此永远不会调用 remove() 方法,但是,我可以在状态栏中看到下载正在运行,因此至少有 1 个下载正在运行。
我的问题简而言之:如何在重新启动后停止运行下载?而且,当下载运行时,为什么 manager.query() 方法会返回一个有 0 个结果的游标?
我知道还有其他有关停止下载的问题,但这些问题无法解决我的问题。
提前致谢。
最佳答案
这个答案的第一部分归功于@Lukesprog
我需要使用setFilterByStatus()
而不是setFilterById()
。交换这两种方法后,我能够成功停止下载,并且 manager.query() 方法返回包含正确下载量的游标。
但是,由于某种原因,显示下载进度的通知在下载停止后并未清除。为了清除通知,您需要调用 manager.remove(c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID)));
两次。
关于java - 如何在系统重新启动后停止正在运行的下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42672721/