在后台下载文件而无需使用Intent打开浏览器 [英] Download a file in background without opening browser with Intent

查看:101
本文介绍了在后台下载文件而无需使用Intent打开浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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的浏览器,并立即执行下载任务。它可以工作,但是会造成干扰,应该在后台进行。

This obviously opens a browser with the URL and goes immedtiatly to a downloading task. It works, but it's interruptive and should happen in the background.

还有另一种方法吗?

推荐答案

您可以简单地将 DownloadManager 用于此任务,

You can use simply DownloadManager for this task,


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

The DownloadManager is a system service that handles long-running HTTP downloads. Clients may request that a URI be downloaded to a particular destination file. The download manager will conduct the download in the background, taking care of HTTP interactions and retrying downloads after failures or across connectivity changes and system reboots.

例如,

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 文件中,

And you also have to add WRITE_EXTERNAL_STORAGE permission in your AndroidManifest file that is,

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

这篇关于在后台下载文件而无需使用Intent打开浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆