我使用此代码从网址下载链接并保存到SD卡(智能手机)
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://yourname.com/file.mp3"));
startActivity(intent);
但是在启动此意图后,浏览器打开并在下载后链接
如何在没有打开浏览器的情况下从网址下载?
答案 0 :(得分:1)
如果要在后台下载,请使用DownloadManager
,因为使用intent将始终在前台启动浏览器。使用DownloadManager的简单教程是
http://blog.vogella.com/2011/06/14/android-downloadmanager-example/
或者你也可以看这里
http://www.compiletimeerror.com/2013/11/download-manager-in-android-with-example.html#.VZDtUfmqqko
答案 1 :(得分:0)
尝试此代码将此功能放在您的Activity中并传递所需的参数,此功能会自动启动下载过程,保存此功能后,您将下载的文件作为文件返回。
public File downloadFile(Context context, String url, String filename) {
File direct = new File(Environment.getExternalStorageDirectory() + "/" + "Your_Foldername");
if (!direct.exists()) {
direct.mkdirs();
} else {
File file = new File(Environment.getExternalStorageDirectory() + "/" + "Your_Foldername" + "/" + filename);
if(file.exists())
file.delete();
}
DownloadManager mgr = (DownloadManager) context.getApplicationContext().getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle(context.getResources().getString(R.string.app_name))
.setDescription("Downloading Share Image for " + context.getResources().getString(R.string.app_name))
.setDestinationInExternalPublicDir("/" + "Your_Foldername", filename);
mgr.enqueue(request);
return direct;
}