问题原因是应用被系统销毁后,下载请求的上下文也被销毁,导致DownloadManager不能继续下载。解决方法是将下载请求的上下文保存到SharedPreferences中,在应用重新启动后,从SharedPreferences中读取上下文并重新创建DownloadManager,继续下载。
示例代码:
保存下载请求的上下文:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = prefs.edit(); editor.putString("download_context", downloadContext); editor.commit();
从SharedPreferences中读取上下文并重新创建DownloadManager:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String downloadContext = prefs.getString("download_context", null); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); long id = downloadManager.enqueue(request); if(downloadContext != null) { downloadManager.remove(id); DownloadManager.Request req = new DownloadManager.Request(Uri.parse(url)); req.addRequestHeader("Content-Type", "application/json"); req.setTitle(fileName); req.setDescription(description); req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); req.setVisibleInDownloadsUi(true); req.setMimeType(mimeType); req.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName); req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE); req.setAllowedOverRoaming(true); req.setAllowedOverMetered(true); req.allowScanningByMediaScanner(); req.setRequiresCharging(false); req.setRequiresDeviceIdle(false); req.setDestinationInExternalFilesDir(OfflineDownloadManager.appContext, Environment.DIRECTORY_DOWNLOADS, fileName); downloadManager.enqueue(req); } else { editor.putString("download_context", String.valueOf(id)); editor.commit(); }