Android WebView Problem Summary and workaround

Source: Internet
Author: User

Android WebView FAQ Solution Rollup:

1, Android webview background set to transparent invalid

WebView is a handy, powerful control, but because the background color of WebView is white by default, it can appear abrupt in some situations (such as the background is black).
At this point I think of setting the background of webview to be transparent, so that it can be integrated with its background.
In the 2. Under the platform of X, the webview background is generally set to transparent as follows:
Wvcontent.setbackgroundcolor (0);
However, when the program is used on 4.0, it is found that this setup method is not possible, even if the background is set to 0, the original default white background is displayed.
Through the online search, found that it was due to hardware acceleration, the thought of using code to close the current WebView hardware acceleration, the method is as follows:
Wvcontent.setlayertype (View.layer_type_software,null);
Then there are new problems, if you want to set up through this code, the minimum version of the SDK (Android 3.0) will not compile properly
You need to set android:layertype= "Software" in the layout file.
Tested to work in 4.0 and 2.2, WebView transparent background setting was successful

2. Audio is played in the WebView page and audio is still playing after exiting activity

Need to call Webview.destroy () in the activity's ondestory ();
However, a direct call may cause the following error:

06-10 15:01:11.402:e/viewrootimpl (7502): senduseractionevent () MView = = null 06-10 15:01:26.818:e/webview (7502): java. Lang.  Throwable:Error:WebView.destroy () called while still attached! 06-10 15:01:26.818:e/webview (7502): at Android.webkit.WebViewClassic.destroy (webviewclassic.java:4142) 06-10 15:01:26.818:e/webview (7502): at Android.webkit.WebView.destroy (webview.java:707) 06-10 15:01:26.818:e/webview ( 7502): At Com.didi.taxi.ui.webview.OperatingWebViewActivity.onDestroy (operatingwebviewactivity.java:236) 06-10 15:01:26.818:e/webview (7502): at Android.app.Activity.performDestroy (activity.java:5543) 06-10 15:01:26.818:e/ WebView (7502): at Android.app.Instrumentation.callActivityOnDestroy (instrumentation.java:1134) 06-10 15:01:26.818: E/webview (7502): at Android.app.ActivityThread.performDestroyActivity (activitythread.java:3619) 06-10 15:01:26.818 : E/webview (7502): at Android.app.ActivityThread.handleDestroyActivity (activitythread.java:3654) 06-10 15:01:26.818 : E/webview (7502): AT android.app.activitythread.access$1300 (activitythread.java:159) 06-10 15:01:26.818:e/webview (7502): at Android.app.activitythread$h.handlemessage (activitythread.java:1369) 06-10 15:01:26.818:e/webview (7502): at Android.os.Handler.dispatchMessage (handler.java:99) 06-10 15:01:26.818:e/webview (7502): at Android.os.Looper.loop ( looper.java:137) 06-10 15:01:26.818:e/webview (7502): at Android.app.ActivityThread.main (activitythread.java:5419) 06-10 15:01:26.818:e/webview (7502): at Java.lang.reflect.Method.invokeNative (Native Method) 06-10 15:01:26.818:e/ WebView (7502): at Java.lang.reflect.Method.invoke (method.java:525) 06-10 15:01:26.818:e/webview (7502): at Com.android.internal.os.zygoteinit$methodandargscaller.run (zygoteinit.java:1187) 03-10 15:01:26.818:e/webview ( 7502): At Com.android.internal.os.ZygoteInit.main (zygoteinit.java:1003) 06-10 15:01:26.818:e/webview (7502): at Dalvik.system.NativeStart.main (Native Method)
as shown above, WebView is still bound to the activity when WebView calls Destory. This is because the context object that was passed in to the activity when the custom WebView was built, you need to first remove the webview from the parent container. And then destroy Webview:rootLayout.removeView (WebView);

3. WebView retains the zoom function but hides the zoom control:

Mwebview.getsettings (). Setsupportzoom (true);  Mwebview.getsettings (). Setbuiltinzoomcontrols (true);  if (Deviceutils.hashoneycomb ())  mwebview.getsettings (). Setdisplayzoomcontrols (false);  
Note: Setdisplayzoomcontrols is the new API in Android 3.0.

4. Custom error display interface for WebView:

Overwrite the Onreceivederror () method in Webviewclient:

/** * Displays the custom error prompt page, with a view overlay in 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) {Merror  View.setvisibility (view.visible);  Super.onreceivederror (view, ErrorCode, description, Failingurl);  }

5. WebView Cookie Cleaning:

Cookiesyncmanager.createinstance (this);   Cookiesyncmanager.getinstance (). Startsync ();   Cookiemanager.getinstance (). Removesessioncookie ();   
but Cookiemanager is obsolete and is not recommended for use.
The documentation prompts the WebView now automatically syncs cookies as necessary.

6. Clean up the cache and historical records:

Webview.clearcache (true);   Webview.clearhistory ();  M_webview.loaddatawithbaseurl (NULL, result, "text/html", "Utf-8", null);

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

The getscrolly () method returns the distance from the top of the entire page of the current visible area, that is, the distance the current content scrolls.
The GetHeight () or Getbottom () method returns the height of the current WebView container.
Getcontentheight returns the height of the entire HTML, but is not the same as the height of the current entire page, because WebView has the zoom function, so the height of the current entire page should actually be the height of the original HTML multiplied by the scale. Therefore, the corrected result, the exact method of judging should be:
if (webview.getcontentheight*webview.getscale () = = (Webview.getheight () +webview.getscrolly ()))
{//already at bottom}

8. URL interception:

Android WebView is not blocking the fragment jump within the page. But the URL jumps, also causes the page to refresh, the H5 page experience drops again. Can only inject JS method to WebView.

9. Handle Non-hyperlink requests (such as AJAX requests) in WebView:

Sometimes you need to add a request header, but a non-hyperlink request, there is no way to intercept shouldoverrinding and adding the request header with the Webview.loadurl (String url,hashmap Headers) method
At present, a temporary solution is used:
You first need to add a special tag/protocol to the URL, such as intercepting the corresponding request in the Onwebviewresource method, and then adding the request header to the end of the URL in a Get form
In the Shouldinterceptrequest () method, you can intercept all the resource requests in the Web page, such as loading JS, images, Ajax requests, etc.

@SuppressLint ("Newapi")  @Override public  webresourceresponse shouldinterceptrequest (WebView view,string URL) {      //non-hyperlinks (such as AJAX) requests cannot be directly added to the request header, now stitching to the end of the URL, here stitching an IMEI as example      String ajaxurl = URL;      As identified: Req=ajax      if (url.contains ("Req=ajax")) {         Ajaxurl + = "&imei=" + Imei;      }      Return super.shouldinterceptrequest (view, Ajaxurl);    }  

10. 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 ();//The page is displayed when the picture is requested       meventlistener.onwebviewevent ( Customwebview.this, Onwebvieweventlistener.event_on_hide_progress, View.geturl ());       }      Super.onloadresource (view, URL);  }  

11. Block off long press events because the WebView will call the system's copy control on time:

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

12. Join Flash support in WebView:

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

13, WebView on Android4.4 's phone onpagefinished () callback will be called more than once

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

14, need to get the title of the Web page to set their own interface title and related issues:

You need to set 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 on the Xiaomi 3 phone, when the Webview.goback () fallback, and did not trigger Onreceivetitle (), which will cause the title is still the title of the previous sub-page, did not switch back.
This can be handled in two ways:
(1) Can be determined WebView sub-page only two levels of pages, no deeper level, here only need to determine whether the current page is the original main page, you can GoBack, as long as the title is set back.
(2) There may be multi-level pages in WebView or later may add multiple pages, this situation is more complicated to handle:
Because the normal sequential loading situation onreceivetitle is bound to trigger, so it is necessary to maintain a URL stack webview loading and the URL and title mapping relationship then need a ArrayList to keep the loaded URL, A hashmap to save the URL and the corresponding title.
When loading in normal order, save the URL and the corresponding title, remove the current URL and remove the URL of the Web page that will be rolled back to, webview the fallback. Find the corresponding title to set it up. Here is another point, when loading error, such as no network, then Onreceivetitle gets the title is not found in the page, it is recommended that when triggering onreceiveerror, do not use the obtained title.

15, WebView due to addjavascriptinterface () caused by security problems.

This problem is mainly due to malicious JS code injection, especially on phones that have root privileges, which may be exploited by malicious programs to install or uninstall applications.
For detailed information, refer to: Https://github.com/pedant/safe-java-js-webview-bridge, the project uses Onjsprompt () instead of Addjavascriptinterface () , and an asynchronous callback is added
A good solution to WebView JS injection security issues.


Welcome to scan Two-dimensional code, learn from each other




Android WebView Problem Summary and workaround

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.