Android WebView常见问题及解决方案汇总

发布时间:2025-08-20 点击:5
就目前而言,如何应对版本的频繁更新呢,又如何灵活多变地展示我们的界面呢,这又涉及到了web app与native app之间孰优孰劣的争论. 于是乎,一种混合型的app诞生了,灵活多变的部分,如淘宝商城首页的活动页面,一集凡客诚品中我们都可以见到web 页面与native页面的混合,既利用了web app的灵活易更新,也借助了native app本身的效率.
当然,就会用到webview这样的一个控件,这里,我把自己使用过程中遇到的一些问题整理下来.
首先上张图对webview进行一个基本的回顾:
以上思维导图原文件下载地址:
http://download.csdn.net/detail/t12x3456/6509195
然后看一下具体的问题及解决方案:
1.为webview自定义错误显示界面:
覆写webviewclient中的onreceivederror()方法:
[java]view plaincopy
/** *显示自定义错误提示页面,用一个view覆盖在webview */ protectedvoidshowerrorpage(){ linearlayoutwebparentview=(linearlayout)mwebview.getparent(); initerrorpage(); while(webparentview.getchildcount()>1){ webparentview.removeviewat(0); } linearlayout.layoutparamslp=newlinearlayout.layoutparams(layoutparams.fill_parent,layoutparams.fill_parent); webparentview.addview(merrorview,0,lp); miserrorpage=true; } protectedvoidhideerrorpage(){ linearlayoutwebparentview=(linearlayout)mwebview.getparent(); miserrorpage=false; while(webparentview.getchildcount()>1){ webparentview.removeviewat(0); } } protectedvoidiniterrorpage(){ if(merrorview==null){ merrorview=view.inflate(this,r.layout.online_error,null); buttonbutton=(button)merrorview.findviewbyid(r.id.online_error_btn_retry); button.setonclicklistener(newonclicklistener(){ publicvoidonclick(viewv){ mwebview.reload(); } }); merrorview.setonclicklistener(null); } }
[java]view plaincopy
[java]view plaincopy
[java]view plaincopy
@override publicvoidonreceivederror(webviewview,interrorcode,stringdescription,stringfailingurl){ <spanstyle=white-space:pre></span> <spanstyle=white-space:pre></span>merrorview.setvisibility(view.visible); <spanstyle=white-space:pre></span>super.onreceivederror(view,errorcode,description,failingurl); }
2.webview cookies清理: [java]view plaincopy
cookiesyncmanager.createinstance(this); cookiesyncmanager.getinstance().startsync(); cookiemanager.getinstance().removesessioncookie();
3.清理cache 和历史记录:
[java]view plaincopy
webview.clearcache(true); webview.clearhistory();
4.判断webview是否已经滚动到页面底端: [java]view plaincopy
getscrolly()方法返回的是当前可见区域的顶端距整个页面顶端的距离,也就是当前内容滚动的距离. getheight()或者getbottom()方法都返回当前webview这个容器的高度 getcontentheight返回的是整个html的高度,但并不等同于当前整个页面的高度,因为webview有缩放功能,所以当前整个页面的高度实际上应该是原始html的高度再乘上缩放比例.因此,更正后的结果,准确的判断方法应该是: if(webview.getcontentheight*webview.getscale()==(webview.getheight()+webview.getscrolly())){//已经处于底端}
5.url拦截:
android webview是拦截不到页面内的fragment跳转的。但是url跳转的话,又会引起页面刷新,h5页面的体验又下降了。只能给webview注入js方法了。
6.处理webview中的非超链接请求(如ajax请求):
有时候需要加上请求头,但是非超链接的请求,没有办法再shouldoverrinding中拦截并用webview.loadurl(string url,hashmap headers)方法添加请求头
目前用了一个临时的办法解决:
首先需要在url中加特殊标记/协议, 如在onwebviewresource方法中拦截对应的请求,然后将要添加的请求头,以get形式拼接到url末尾
在shouldinterceptrequest()方法中,可以拦截到所有的网页中资源请求,比如加载js,图片以及ajax请求等等
ex:
[java]view plaincopy
@suppresslint(newapi) @override publicwebresourceresponseshouldinterceptrequest(webviewview,stringurl){ //非超链接(如ajax)请求无法直接添加请求头,现拼接到url末尾,这里拼接一个imei作为示例 stringajaxurl=url; //如标识:req=ajax if(url.contains(req=ajax)){ ajaxurl+=&imei=+imei; } returnsuper.shouldinterceptrequest(view,ajaxurl); }
7.在页面中先显示图片:
[java]view plaincopy
@override publicvoidonloadresource(webviewview,stringurl){ meventlistener.onwebviewevent(customwebview.this,onwebvieweventlistener.event_on_load_resource,url); if(url.indexof(.jpg)>0){ hideprogress();//请求图片时即显示页面 meventlistener.onwebviewevent(customwebview.this,onwebvieweventlistener.event_on_hide_progress,view.geturl()); } super.onloadresource(view,url); }
8.屏蔽掉长按事件 因为webview长按时将会调用系统的复制控件:
[java]view plaincopy
mwebview.setonlongclicklistener(newonlongclicklistener(){ @override publicbooleanonlongclick(viewv){ returntrue; } });
9.在webview加入 flash支持:
[java]view plaincopy
stringtemp=<html><bodybgcolor=\+black +\><br/><embedsrc=\+url+\width=\+100% +\height=\+90%+\scale=\+noscale +\type=\+application/x-shockwave-flash +\></embed></body></html>; stringmimetype=text/html; stringencoding=utf-8; web.loaddatawithbaseurl(null,temp,mimetype,encoding,);
10.webview保留缩放功能但隐藏缩放控件:
[java]view plaincopy
mwebview.getsettings().setsupportzoom(true); mwebview.getsettings().setbuiltinzoomcontrols(true); if(deviceutils.hashoneycomb()) mwebview.getsettings().setdisplayzoomcontrols(false);
注意:setdisplayzoomcontrols是在android 3.0中新增的api.
这些是目前我整理出来的一些注意事项和问题解决方案,也欢迎大家多提一些关于webview的问题,如果有合适的解决方案,我会直接更新到这篇文章.
8月份更新:
11.webview 在android4.4的手机上onpagefinished()回调会多调用一次(具体原因待追查)
需要尽量避免在onpagefinished()中做业务操作,否则会导致重复调用,还有可能会引起逻辑上的错误.
12.需要通过获取web页中的title用来设置自己界面中的title及相关问题:
需要给webview设置 webchromeclient,并在onreceivetitle()回调中获取
[java]view plaincopy
webchromeclientwebchromeclient=newwebchromeclient(){ @override publicvoidonreceivedtitle(webviewview,stringtitle){ super.onreceivedtitle(view,title); txttitle.settext(title); } };
但是发现在小米3的手机上,当通过webview.goback()回退的时候,并没有触发onreceivetitle(),这样会导致标题仍然是之前子页面的标题,没有切换回来.
这里可以分两种情况去处理:
(1) 可以确定webview中子页面只有二级页面,没有更深的层次,这里只需要判断当前页面是否为初始的主页面,可以goback的话,只要将标题设置回来即可.
(2)webview中可能有多级页面或者以后可能增加多级页面,这种情况处理起来要复杂一些:
因为正常顺序加载的情况onreceivetitle是一定会触发的,所以就需要自己来维护webview loading的一个url栈及url与title的映射关系
那么就需要一个arraylist来保持加载过的url,一个hashmap保存url及对应的title.
正常顺序加载时,将url和对应的title保存起来,webview回退时,移除当前url并取出将要回退到的web 页的url,找到对应的title进行设置即可.
这里还要说一点,当加载出错的时候,比如无网络,这时onreceivetitle中获取的标题为 找不到该网页,因此建议当触发onreceiveerror时,不要使用获取到的title.
13.webview因addjavascriptinterface()引起的安全问题.
这个问题主要是因为会有恶意的js代码注入,尤其是在已经获取root权限的手机上,一些恶意程序可能会利用该漏洞安装或者卸载应用.
关于详细的情况可以参考下面这篇文章:
.http://blog.csdn.net/leehong2005/article/details/11808557
还有一个开源项目可以参考:https://github.com/pedant/safe-java-js-webview-bridge, 该项目利用onjsprompt() 替代了addjavascriptinterface(),(解决方案类似上述参考的博客)同时增加了异步回调,
很好地解决了webview js注入的安全问题.
10月份更新:
14.webview页面中播放了音频,退出activity后音频仍然在播放
需要在activity的ondestory()中调用
[java]view plaincopy
webview.destroy();
但是直接调用可能会引起如下错误:
[java]view plaincopy
10-1015:01:11.402:e/viewrootimpl(7502):senduseractionevent()mview==null 10-1015:01:26.818:e/webview(7502):java.lang.throwable:error:webview.destroy()calledwhilestillattached! 10-1015:01:26.818:e/webview(7502):atandroid.webkit.webviewclassic.destroy(webviewclassic.java:4142) 10-1015:01:26.818:e/webview(7502):atandroid.webkit.webview.destroy(webview.java:707) 10-1015:01:26.818:e/webview(7502):atcom.didi.taxi.ui.webview.operatingwebviewactivity.ondestroy(operatingwebviewactivity.java:236) 10-1015:01:26.818:e/webview(7502):atandroid.app.activity.performdestroy(activity.java:5543) 10-1015:01:26.818:e/webview(7502):atandroid.app.instrumentation.callactivityondestroy(instrumentation.java:1134) 10-1015:01:26.818:e/webview(7502
上海网站建设公司,上海网站设计公司全凭实力站稳网络市场
企业网站如何通过SEO优化提高网站排名,看过来
处理网站跳出率的办法?
行业门户网站的內链应该如何建设呢?
网站只做SEO渠道被百度K了我们应该怎么面对?
网站优化每天需要发几篇文章合理呢
一分钟带你了解“用户的各种体验和需求”
香港高防服务器ip的优势有哪些?