使用場(chǎng)景
webview加載網(wǎng)址的時(shí)候 如果碰到非網(wǎng)頁類型,未做處理的話,webview會(huì)報(bào)錯(cuò)(出現(xiàn)瀏覽器崩潰的界面)。
這是因?yàn)閣ebview無法加載非網(wǎng)頁類型界面,導(dǎo)致界面崩潰,但是瀏覽器內(nèi)部有相關(guān)api。
webview.setDownloadListener(DownloadListener listener)
只要設(shè)置這個(gè)監(jiān)聽事件,就可以在要發(fā)生下載請(qǐng)求的時(shí)候,進(jìn)行下載。
使用接口
在DownloadListener這個(gè)接口里可以可以實(shí)現(xiàn)下載的方法。
重寫下載的onDownloadStart()方法就行了
void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength);
//url String:應(yīng)下載的內(nèi)容的完整URL
//userAgent String:用于下載的用戶代理。
//contentDisposition String:Content-disposition http標(biāo)頭,如果存在。
//mimetype String:服務(wù)器報(bào)告的內(nèi)容的mimetype
//contentLength long:服務(wù)器報(bào)告的文件大小
實(shí)現(xiàn)方法
ps:不管用啥方法,都要注意androidM的動(dòng)態(tài)權(quán)限問題;
推薦方案(最方便)
系統(tǒng)自帶的DownloadManager
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
// 允許媒體掃描,根據(jù)下載的文件類型被加入相冊(cè)、音樂等媒體庫
request.allowScanningByMediaScanner();
// 設(shè)置通知的顯示類型,下載進(jìn)行時(shí)和完成后顯示通知
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// 設(shè)置通知欄的標(biāo)題,如果不設(shè)置,默認(rèn)使用文件名
request.setTitle("下載完成");
// 設(shè)置通知欄的描述
// request.setDescription("This is description");
// 允許在計(jì)費(fèi)流量下下載
request.setAllowedOverMetered(true);
// 允許該記錄在下載管理界面可見
request.setVisibleInDownloadsUi(true);
// 允許漫游時(shí)下載
request.setAllowedOverRoaming(true);
String fileName = URLUtil.guessFileName(url, contentDisposition, mimeType);
Log.e("fileName:{}", fileName);
request.setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory() + "/Download/", fileName);
final DownloadManager downloadManager = (DownloadManager) iWebView.getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
// 添加一個(gè)下載任務(wù)
long downloadId = downloadManager.enqueue(request);
ps:不需要判斷androidN的URI的問題哦
另外也可以用okhttps進(jìn)行下載也很方便~(稍微注意下androidN的問題)