Android WebView FAQ and Solution Rollup _android

Source: Internet
Author: User

Android WebView FAQ Solution Rollup:

For now, how to deal with the frequent update of the version and how to display our interface flexibly, which is related to the pros and cons of web app and native app. Thus, a hybrid app was born, flexible parts, such as Taobao Mall homepage Activity page, an episode where we can see Web pages and native pages of the mix, both the use of the Web app's flexible and easy to update, also with the help of the native app itself efficiency.

Of course, we will use a control such as WebView, here, I have to use some of the problems encountered in the process of sorting down.

First, a basic review of WebView is carried out in the previous picture:

Then look at the specific problems and solutions:

1. Custom error display interface for WebView:

Overwrite the Onreceivederror () method in Webviewclient:

/** * Displays a custom error prompt page with a view overlay on WebView * * protected void Showerrorpage () {LinearLayout Webparentview = (linearlayou 
   
  T) 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.on 
    Line_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 Cleaning:

Cookiesyncmanager.createinstance (this);  
Cookiesyncmanager.getinstance (). Startsync ();  

3. Clean cache and historical records:

Webview.clearcache (TRUE);  

4. Determine if WebView has scrolled to the bottom of the page:

The getscrolly () method returns the distance at the top of the entire page from the current visible range, which is the current content scrolling distance.

The GetHeight () or Getbottom () method returns the height of the current WebView container

Getcontentheight returns the height of the entire HTML, but not the height of the current entire page, because the webview has zoom capabilities, so the current entire page

The height should actually be the height of the original HTML multiplied by the scaling scale. Therefore, the correct method of judging the result should be:
if (webview.getcontentheight*webview.getscale () = = (Webview.getheight () +webview.getscrolly ())) {//already at bottom}

5.URL Intercept:

The Android WebView is blocked from fragment jumps within the page. But the URL jumps, will cause the page to refresh, the H5 page experience has dropped again. Can only inject the JS method to WebView.

6. Process non-hyperlink requests in WebView (such as AJAX requests):

Sometimes you need to add a request header, but a request that is not a hyperlink, there is no way to intercept in shouldoverrinding and use the Webview.loadurl (String url,hashmap Headers) method for adding a request header

At present, a temporary solution is used:

First you need to add special tags/protocols in the URL, such as intercepting the corresponding request in the Onwebviewresource method, and then the request header to be added to the end of the URL in get form

In the Shouldinterceptrequest () method, you can intercept resource requests in all Web pages, such as loading JS, images, Ajax requests, and so on.

Ex:

@SuppressLint ("Newapi") 
@Override public 
webresourceresponse shouldinterceptrequest (WebView view,string URL) { 
  //non-hyperlink (such as Ajax) request cannot directly add the request header, now stitching to the end of the URL, where stitching a imei as an example 
 
  String ajaxurl = URL; 
  such as ID: Req=ajax 
  if (url.contains ("Req=ajax")) { 
    Ajaxurl + = "&imei=" + Imei; 
  } 
 
  Return super.shouldinterceptrequest (view, ajaxurl); 
 
 

7. Display the picture first in the page:

@Override public 
void Onloadresource (webview view, String URL) { 
 meventlistener.onwebviewevent ( Customwebview.this, Onwebvieweventlistener.event_on_load_resource, url); 
  if (Url.indexof (". jpg") > 0) { 
   hideprogress ()///////////////( 
   Customwebview.this, Onwebvieweventlistener.event_on_hide_progress, View.geturl ()); 
   } 
  Super.onloadresource (view, URL); 
 

8. Shielding off the long press event because WebView will call the system's replication controls on time:

Mwebview.setonlongclicklistener (New Onlongclicklistener () { 
      
     @Override public 
     boolean Onlongclick (View v) { return 
       true; 
     } 
   }); 

9. Add flash support in WebView:

The String temp = "+ "> </embed></body> 
 

10.WebView Keep zooming but hide zoom controls:

Mwebview.getsettings (). Setsupportzoom (true); 
    Mwebview.getsettings (). Setbuiltinzoomcontrols (true); 
    if (Deviceutils.hashoneycomb ()) 
       mwebview.getsettings (). Setdisplayzoomcontrols (false); 

Note: Setdisplayzoomcontrols is a new API in Android 3.0.

These are the present I sorted out some attention matters and the problem solution, also welcome everybody to mention some about webview the question, if has the suitable solution, I will directly update to this article.

11.WebView on Android4.4 's phone onpagefinished () callback will be called more than once (for specific reasons to be traced)

It is necessary to avoid doing business operations in onpagefinished (), otherwise it can cause repeated calls and may cause logical errors.

12. You need to use the title in your Web page to set the title and related issues in your own interface:

You need to set the webchromeclient for WebView and get it in the Onreceivetitle () callback

Webchromeclient webchromeclient = new Webchromeclient () {  
      @Override public  
      void Onreceivedtitle (WebView view, String title) {  
        super.onreceivedtitle (view, title);  
         
        Txttitle.settext (title);  
      }  
  
    ;  

But found in the Millet 3 mobile phone, when through Webview.goback () back, and did not trigger the Onreceivetitle (), which will cause the title is still the previous sub page title, did not switch back.

There are two ways to handle this:

(1) can determine the WebView neutron page only two level page, no deeper level, here only need to determine whether the current page is the initial main page, you can GoBack, as long as the title set back.

(2) WebView may have multilevel pages or may later increase the number of multilevel pages, this situation is more complicated to deal with:

Because the normal loading of the situation Onreceivetitle is bound to trigger, so you need to maintain the webview loading a URL stack and URL and title mapping relationship

Then you need a ArrayList to keep the loaded URL, a hashmap to save the URL and the corresponding title.

In normal order load, the URL and the corresponding title saved, WebView back, remove the current URL and take out the URL of the Web page to be rolled back, find the corresponding title to set it.

Here also to say that when the load error, such as no network, then Onreceivetitle get the title of the page is not found, it is recommended that when the trigger Onreceiveerror, do not use the obtained title.

13.WebView security problems caused by addjavascriptinterface ().

This problem is mainly due to malicious JS code injection, especially on the phone that has access to root permissions, some malicious programs may use the vulnerability to install or uninstall applications.

Audio is played on the 14.WebView page and audio is still playing after exiting the activity

Needs to be called in the Ondestory () of the activity

Webview.destroy (); 

However, a direct call can cause the following error:

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)

As shown above, when WebView calls Destory, WebView is still bound to the activity. This is because custom WebView is passed into the context object of the activity at build time, so you need to remove the webview from the parent container first. And then destroy the WebView:

Rootlayout.removeview (WebView); 

WebView for replication sharing related functions by customizing menus

This feature can be done in two ways first:

(1) completed in JS:

Handling Android.selection.longTouch

(2) Android layer processing:

First of all, using Ontouchlistener implementation monitoring, and then implement WebView context menu, the last Call WebView in the Emulateshiftheld (), in order to fit the different versions of Android, it is best to use the reflection method call.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.