WebView 显示广告页面下载文件按钮无反应的解决方法

时间:2023-02-09 20:17:20

用WebView显示样式丰富的3G页面,不仅显示效果,实用性强,还能缩短宝贵的开放时间,但是今天发现广告页面有个下载按钮点击后并没有弹出下载提示框,

百度后有人说是“因为WebView默认没有开启文件下载的功能,需要setDownloadListener”,但是查看setDownloadListener源码注释,发现这个方法只是替换了

current handler,说明webView默认是有文件下载功能的,但是为什么我的项目中点击没有反应了,原来我给webView设置了新的webViewClient(其他的Client也是类似的)

mWebView.setWebViewClient(new MyWebViewClient());

这就清晰了,因为WebViewClient的注释中这样说

Give the host application a chance to take over the control when a new
url is about to be loaded in the current WebView. If WebViewClient is not
provided, by default WebView will ask Activity Manager to choose the
proper handler for the url. If WebViewClient is provided, return true
means the host application handles the url, while return false means the
current WebView handles the url.
This method is not called for requests using the POST "method".

所以,如果点击下载按钮没有反应,首先检查是否自己设置了新的WebViewClient


接着,我们再来验证下 webView默认是有文件下载功能的 这句话
很简单,注释掉我们自定义的WebViewClient,或者删除这句话,仅仅让webview load 一个有下载链接的url,这时我们都明白webview加载的网页中的其他链接在我们点击时会
用系统默认的打开方式,我在代码注释了下面这行代码,果然,系统默认的下载器就开始下载网页中的文件了

mWebView.setWebViewClient(new MyWebViewClient());


所以,我们明白了webview默认是有文件是有文件下载功能的,如果你设置了webviewClient,却没有处理下载的请求,这样点击下载就无法处理,所以没反应,简单的方法直接设置setDownloadListener,用默认下载器下载即可,


/**
* Registers the interface to be used when content can not be handled by
* the rendering engine, and should be downloaded instead. This will replace
* the current handler.
*
* @param listener an implementation of DownloadListener
*/
public void setDownloadListener(DownloadListener listener) {
checkThread();
mProvider.setDownloadListener(listener);
}

mWebView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Log.w(TAG, url);
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});

当然,在onDownloadStart 方法中获取到下载地址后,我们就可以按照自己的意愿处理了,可以在代码中自己下载,等等,都是so easy...