在开发中WebView不会主动去下载文件,但webView提供了下载文件的的接口
webView.setOnDownloadListener(new OnDownloadListener(){
});
第一种:实现Java代码下载
其中有一个回调方法返回要下载文件的url,我们可以使用该url在native中实现网络下载
class MyDownloadStart implements DownloadListener{ @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { // TODO Auto-generated method stub //调用自己的下载方式 // new HttpThread(url).start(); } }
第二种:使用系统下载器下载
class MyDownloadStart implements DownloadListener{ @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength){ AppUtils.LogD(mimetype); // download file DownloadManager downloadManager = ((DownloadManager) activity .getSystemService(Activity.DOWNLOAD_SERVICE)); Request request = new Request(Uri.parse(url)); // set request header, 如session等 www.2cto.com request.addRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); request.addRequestHeader("Accept-Language", "en-us,en;q=0.5"); request.addRequestHeader("Accept-Encoding", "gzip, deflate"); request.addRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); request.addRequestHeader("Cache-Control", "max-age=0"); String host = ""; try { host = new URL(url).getHost(); } catch (MalformedURLException e) { e.printStackTrace(); } String cookieStr = CookieManager.getInstance().getCookie(host); if (!AppUtils.isEmpty(cookieStr)) { request.addRequestHeader("Cookie", cookieStr + "; AcSe=0"); } // generate filename dynamically String fileName = contentDisposition.replaceFirst( "attachment; filename=", ""); request.setDestinationInExternalPublicDir( Environment.DIRECTORY_DOWNLOADS, fileName); downloadManager.enqueue(request);});
第三种:使用默认浏览器下载
将获得到的url转为 uri,然后调用系统的浏览器去下载,这种方式可以看见文件下载进度条
class MyDownloadStart implements DownloadListener{ @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { // TODO Auto-generated method stub //调用系统浏览器下载 Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } }