无需使用Intent打开浏览器即可在后台下载文件

时间:2018-01-06 18:18:48

标签: android url download

try {

    String url = "MY URL"
    i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    view.openDownloadIntent(i); // startsActivity
}
catch (NullPointerException e) {
    view.showMissingDocumentMessage("Failed");
}

这显然会打开一个带有URL的浏览器,并立即转到下载任务。它有效,但它是中断性的,应该在后台发生。

还有其他办法吗?

1 个答案:

答案 0 :(得分:1)

您只需使用DownloadManager执行此任务,

  

DownloadManager是一个处理长时间运行的系统服务   HTTP下载。客户端可以请求将URI下载到a   特定目标文件。下载管理器将执行   在后台下载,负责HTTP交互和   在故障或连接更改后重试下载   系统重启。

例如,

DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

                request.setTitle("Downloading...");  //set title for notification in status_bar
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);  //flag for if you want to show notification in status or not

                //String nameOfFile = "YourFileName.pdf";    //if you want to give file_name manually

                String nameOfFile = URLUtil.guessFileName(url, null, MimeTypeMap.getFileExtensionFromUrl(url)); //fetching name of file and type from server

                File f = new File(Environment.getExternalStorageDirectory() + "/" + yourAppFolder);       // location, where to download file in external directory
                if (!f.exists()) {
                    f.mkdirs();
                }
                request.setDestinationInExternalPublicDir(yourAppFolder, nameOfFile);
                DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                downloadManager.enqueue(request);

您还必须在WRITE_EXTERNAL_STORAGE文件中添加AndroidManifest权限,

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />