Android中WebView的一个小问题:
昨天用WebView加载网页时,点击下载按钮无法响应下载动作。
排除问题:
首先想到的当然是网页本身的问题,用PC加载网页后法案现阔以正常下载。那这样的话问题就在WebView上了。
思考问题:
小弟这种小弱鸡当然选择进技术群(不是水群),问一下大佬是最快速有效合理的方法,并且还能帮大佬巩固一下小知识点。
询问之后知道WebView有一个DownLoadListener方法。
那咱们的解决方式就是自定义DownLoadListener,然后再通过WebView的setDownLoadListener关联DownLoadListener。
DownLoadListener源码:
package android.webkit;
public interface DownloadListener {
/**
* Notify the host application that a file should be downloaded
* (onDownLoadStart:将一个文件下载到主机应用程序中)
* @param url The full url to the content that should be downloaded
* (url链接到应该下载的内容的完整url,也就是apk下载路径。)
* @param userAgent the user agent to be used for the download.
* @param contentDisposition Content-disposition http header, if present.(将用于下载的用户代理。不知道怎么用,目前用不到。)
* @param mimetype The mimetype of the content reported by the server(mimetype是服务器报告的内容的mimetype)
* @param contentLength The file size reported by the server
* (内容长度由服务器报告的文件大小)
*/
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype, long contentLength);
}
解决问题:
首先自定义DownloadListener,在重写的onDownLoadStart方法中判断url的后缀是否是.apk,如果是的话调用系统下载APK:
/*
*自定义DownLoadListener
*/
class MyDownLoad implements DownloadListener {
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype, long contentLength) {
if (url.endsWith(".apk")) {
/**
* 通过系统下载apk
*/
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);
}
}
}
//WebView设置下载监听
webView.setDownloadListener(new MyDownLoad());
好了,现在加载网页就可以正常的响应网页上的点击事件了。
如有问题请多指正,您的指正使我更我正确的前行.
本文介绍了一个关于Android中WebView无法响应下载按钮的小问题及其解决方案。通过自定义DownloadListener并实现onDownloadStart方法,可以成功实现对特定文件类型的下载处理。
1086

被折叠的 条评论
为什么被折叠?



