当前位置: 移动技术网 > IT编程>移动开发>Android > Android中WebView常见问题及解决方案汇总

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

2019年07月24日  | 移动技术网IT编程  | 我要评论

1688批发,running man e61,猛虎威龙

android webview常见问题解决方案汇总:

就目前而言,如何应对版本的频繁更新呢,又如何灵活多变地展示我们的界面呢,这又涉及到了web app与native app之间孰优孰劣的争论. 于是乎,一种混合型的app诞生了,灵活多变的部分,如淘宝商城首页的活动页面,一集凡客诚品中我们都可以见到web页面与native页面的混合,既利用了web app的灵活易更新,也借助了native app本身的效率.

当然,就会用到webview这样的一个控件,这里,我把自己使用过程中遇到的一些问题整理下来.

首先上张图对webview进行一个基本的回顾:

然后看一下具体的问题及解决方案:

1.为webview自定义错误显示界面:

覆写webviewclient中的onreceivederror()方法:

/** 
 * 显示自定义错误提示页面,用一个view覆盖在webview 
 */ 
protected void showerrorpage() { 
  linearlayout webparentview = (linearlayout)mwebview.getparent(); 
   
  initerrorpage(); 
  while (webparentview.getchildcount() > 1) { 
    webparentview.removeviewat(0); 
  } 
  linearlayout.layoutparams lp = new linearlayout.layoutparams(layoutparams.fill_parent,layoutparams.fill_parent); 
  webparentview.addview(merrorview, 0, lp); 
  miserrorpage = true; 
} 
protected void hideerrorpage() { 
  linearlayout webparentview = (linearlayout)mwebview.getparent(); 
   
  miserrorpage = false; 
  while (webparentview.getchildcount() > 1) { 
    webparentview.removeviewat(0); 
  } 
} 
 
 
  protected void initerrorpage() { 
  if (merrorview == null) { 
    merrorview = view.inflate(this, r.layout.online_error, null); 
    button button = (button)merrorview.findviewbyid(r.id.online_error_btn_retry); 
    button.setonclicklistener(new onclicklistener() { 
      public void onclick(view v) { 
        mwebview.reload(); 
      } 
    }); 
    merrorview.setonclicklistener(null); 
  } 
} 
@override 
public void onreceivederror(webview view, int errorcode, string description, string failingurl) { 
<span style="white-space:pre">         </span> 
<span style="white-space:pre">     </span>merrorview.setvisibility(view.visible); 
<span style="white-space:pre">     </span>super.onreceivederror(view, errorcode, description, failingurl); 
}   

2.webview cookies清理:

cookiesyncmanager.createinstance(this);  
cookiesyncmanager.getinstance().startsync();  
cookiemanager.getinstance().removesessioncookie(); 

3.清理cache 和历史记录:

webview.clearcache(true);  
webview.clearhistory(); 

4.判断webview是否已经滚动到页面底端:

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:

@suppresslint("newapi") 
@override 
public webresourceresponse shouldinterceptrequest(webview view,string url) { 
  // 非超链接(如ajax)请求无法直接添加请求头,现拼接到url末尾,这里拼接一个imei作为示例 
 
  string ajaxurl = url; 
  // 如标识:req=ajax 
  if (url.contains("req=ajax")) { 
    ajaxurl += "&imei=" + imei; 
  } 
 
  return super.shouldinterceptrequest(view, ajaxurl); 
 
} 

7.在页面中先显示图片:

@override 
public void onloadresource(webview view, string url) { 
 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长按时将会调用系统的复制控件:

mwebview.setonlongclicklistener(new onlongclicklistener() { 
      
     @override 
     public boolean onlongclick(view v) { 
       return true; 
     } 
   }); 

9.在webview加入 flash支持:

string temp = "<html><body bgcolor=\"" + "black" 
        + "\"> <br/><embed src=\"" + url + "\" width=\"" + "100%" 
        + "\" height=\"" + "90%" + "\" scale=\"" + "noscale" 
        + "\" type=\"" + "application/x-shockwave-flash" 
        + "\"> </embed></body></html>"; 
string mimetype = "text/html"; 
string encoding = "utf-8"; 
web.loaddatawithbaseurl("null", temp, mimetype, encoding, ""); 

10.webview保留缩放功能但隐藏缩放控件:

mwebview.getsettings().setsupportzoom(true); 
    mwebview.getsettings().setbuiltinzoomcontrols(true); 
    if (deviceutils.hashoneycomb()) 
       mwebview.getsettings().setdisplayzoomcontrols(false); 

注意:setdisplayzoomcontrols是在android 3.0中新增的api.

这些是目前我整理出来的一些注意事项和问题解决方案,也欢迎大家多提一些关于webview的问题,如果有合适的解决方案,我会直接更新到这篇文章.

11.webview 在android4.4的手机上onpagefinished()回调会多调用一次(具体原因待追查)

需要尽量避免在onpagefinished()中做业务操作,否则会导致重复调用,还有可能会引起逻辑上的错误.

12.需要通过获取web页中的title用来设置自己界面中的title及相关问题:

需要给webview设置 webchromeclient,并在onreceivetitle()回调中获取

webchromeclient webchromeclient = new webchromeclient() {  
      @override  
      public void onreceivedtitle(webview view, string title) {  
        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权限的手机上,一些恶意程序可能会利用该漏洞安装或者卸载应用.

14.webview页面中播放了音频,退出activity后音频仍然在播放

需要在activity的ondestory()中调用

webview.destroy(); 

但是直接调用可能会引起如下错误:

10-10 15:01:11.402: e/viewrootimpl(7502): senduseractionevent() mview == null 
10-10 15:01:26.818: e/webview(7502): java.lang.throwable: error: webview.destroy() called while still attached! 
10-10 15:01:26.818: e/webview(7502):    at android.webkit.webviewclassic.destroy(webviewclassic.java:4142) 
10-10 15:01:26.818: e/webview(7502):    at android.webkit.webview.destroy(webview.java:707) 
10-10 15:01:26.818: e/webview(7502):    at com.didi.taxi.ui.webview.operatingwebviewactivity.ondestroy(operatingwebviewactivity.java:236) 
10-10 15:01:26.818: e/webview(7502):    at android.app.activity.performdestroy(activity.java:5543) 
10-10 15:01:26.818: e/webview(7502):    at android.app.instrumentation.callactivityondestroy(instrumentation.java:1134) 
10-10 15:01:26.818: e/webview(7502):    at android.app.activitythread.performdestroyactivity(activitythread.java:3619) 
10-10 15:01:26.818: e/webview(7502):    at android.app.activitythread.handledestroyactivity(activitythread.java:3654) 
10-10 15:01:26.818: e/webview(7502):    at android.app.activitythread.access$1300(activitythread.java:159) 
10-10 15:01:26.818: e/webview(7502):    at android.app.activitythread$h.handlemessage(activitythread.java:1369) 
10-10 15:01:26.818: e/webview(7502):    at android.os.handler.dispatchmessage(handler.java:99) 
10-10 15:01:26.818: e/webview(7502):    at android.os.looper.loop(looper.java:137) 
10-10 15:01:26.818: e/webview(7502):    at android.app.activitythread.main(activitythread.java:5419) 
10-10 15:01:26.818: e/webview(7502):    at java.lang.reflect.method.invokenative(native method) 
10-10 15:01:26.818: e/webview(7502):    at java.lang.reflect.method.invoke(method.java:525) 
10-10 15:01:26.818: e/webview(7502):    at com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:1187) 
10-10 15:01:26.818: e/webview(7502):    at com.android.internal.os.zygoteinit.main(zygoteinit.java:1003) 
10-10 15:01:26.818: e/webview(7502):    at dalvik.system.nativestart.main(native method) 

如上所示,webview调用destory时,webview仍绑定在activity上.这是由于自定义webview构建时传入了该activity的context对象,因此需要先从父容器中移除webview,然后再销毁webview:

rootlayout.removeview(webview); 
webview.destroy(); 

15. webview长按自定义菜单,实现复制分享相关功能 

这个功能首先可以从两方面完成:

(1) 在js中完成:

处理android.selection.longtouch

(2) 安卓层处理:

首先使用ontouchlistener实现长按实现监听,然后实现webview的context menu,最后调用webview中的emulateshiftheld(),为了适配安卓不同版本,最好使用反射方式调用.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网