安卓系统:在不打开浏览器的情况下启动活动(意图)



我使用此代码从url下载链接并保存到sd卡(whith智能手机)

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://yourname.com/file.mp3"));
startActivity(intent);

但启动此意图后,浏览器打开并下载链接

如何在没有打开浏览器的情况下从url下载?

如果您想在后台下载,请使用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

尝试此代码,将此函数放置在"活动"中并传递所需参数,此函数将自动启动下载过程,并在保存此函数后将下载的文件返回为file。

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;
        }

相关内容

最新更新