WebView中无法下载问题解决方法
时间: 2024-05-01 12:23:36 浏览: 160
WebView 中无法下载的问题一般是因为没有设置相应的下载配置,可以尝试以下解决方法:
1. 在 AndroidManifest.xml 中添加权限:
```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
2. 设置 WebChromeClient,并重写 onDownloadStart 方法:
```java
WebView webView = findViewById(R.id.webView);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimetype);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading file...");
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(), "Downloading File", Toast.LENGTH_LONG).show();
}
});
```
重写 onDownloadStart 方法后,点击 WebView 中的下载链接时,会调用该方法进行下载。
注意:需要在 AndroidManifest.xml 中添加 DOWNLOAD_SERVICE 权限。
```xml
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
```
阅读全文