webView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) { if(mimeType.equals("application/vnd.ms-excel")) { DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setMimeType(mimeType); String cookies = CookieManager.getInstance().getCookie(url); if(cookies != null) { request.addRequestHeader("cookie", cookies); } request.addRequestHeader("User-Agent", userAgent); request.setDescription("Excel文件正在下载"); request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType)); request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType)); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); dm.enqueue(request); Toast.makeText(getApplicationContext(), "Excel文件开始下载", Toast.LENGTH_LONG).show(); } else { webView.loadUrl(url); } } });
String authorities = getApplicationContext().getPackageName() + ".provider"; File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName); Uri uri = FileProvider.getUriForFile(getApplicationContext(), authorities