Android uses WebView to develop common pits

Source: Internet
Author: User

Original link: http://mp.weixin.qq.com/s?__biz=MzAwODE1NTI2MQ==&tempkey=uP3a%2BOgIN7vPbLfJp3BTCl2KabYi1% 2ffbuqekkqd7ixonggn4jfrr81awdwsbof%2fhsice4%2b9o0kjq6lv%2b32psyh46eqaiwj5i%2bxxed% 2bjripwhyfcfbduibpnnlrzdxqac4jv34qtcrbplx6ff3qjtjq%3d%3d&chksm= 1b7278102c05f1068706fba93854af9f4ab7b93e610b5ffee5917dcf378489958605f784c2cf#rd

Android WebView Develop common pits

Today's apps are basically developed using NATIVE+H5, such as the NetEase News Detail page, which will be developed using WebView. This makes it easy to achieve the need for graphic typesetting, and the benefits of hybrid development are obvious.

AC also often uses the WebView control when developing a project, which is convenient to use, but has many problems. The following are the pits that AC has stepped through during development, and hopefully it will be useful for small partners who use this control.

1. WebView cannot display the alert and confirm dialog boxes in HTML

WebView to display the alert and confirm dialog boxes in HTML, you need to implement the Webviewchromclient interface. WebView is just a carrier, a variety of content rendering needs to use webviewchromclient to implement, so set a default base class Webchromeclient on the line

Mwebview.setwebchromeclient (New Webchromeclient ());

Used to bounce alert and so on, if you want to customize the Alert,confirm dialog box, you must override the Onalert and Onconfirm methods

2. The JS method implemented in WebView cannot be called

In the process of implementing WebView and JS interaction, if you encounter the post-click JS method is not responding, you should pay attention to the following issues:

(1) Webview.addjavascriptinterface (new Androidclick (), "app"); This method aliases whether Android is the same as the object name in JS

<div style= "Text-align:center;" ><a onclick= "Window.app.onclick (' www.115.com ')" > content has been automatically optimized for reading, click to view the original text </a></div>

(2) If H5 is prompted by the alert method to prompt the dialog box, WebView need to implement the callback function

Mwebview.setwebchromeclient (New Customwebchromeclient ());

and implement the following alert callback methods, and you can implement a custom dialog box style.

@Override
public boolean Onjsalert (WebView view, string URL, string message, jsresult result) {
Return Super.onjsalert (view, URL, message, result);
Showconfirmdialog (View.getcontext (), message, result, false);
return true;
}

There are similar onjsconfirm methods and so on.

(3) If the published app has been confused, then androidclick this JS and Java interaction class needs proguard.cfg file ignore this class confusion, otherwise confusing JS will not execute.

-keepclassmembers class net.angrycode.js2java.androidclick{*;}

(4) JS Call native method, if the front-end to perform some more time-consuming operation, the front-end code may run in the thread, at this time if the JS method calls native method to do some logical operation, the call will have a problem, although will not crash but will error. The reference workaround is (Mjsinterface is an object injected into the WebView via Addjavainterface)

/**
* Submit Create Request form data
*/
Mjsinterface.setonputapplylistener (JSON-, {
Mwebview.post ((), {
Ensure that native related controls are accessed in the main thread
});
});

3. Quickly open and close the WebView page the control null pointer exception problem occurred

There may be many reasons for this, but if the page control is closed during the webview load and the load thread continues to run, a null pointer exception may occur on the page when the data is returned. This time can be in the Webviewclient and Webviewchrome interface in the Onpagestart and Onpagefinish,onprogresschange these callback methods to determine whether the current page exists, if not exist directly return.

@Override
public void onpagefinished (WebView view, String URL) {
if (getactivity () = = NULL | | getactivity (). isfinishing ()) {
Return
}
super.onpagefinished (view, URL);
//...
}

4, WebView and JS interaction caused by the security problems

4.2 The following systems recommend an open source project Https://github.com/pedant/safe-java-js-webview-bridge

Of course, webview security more than this, you can own Baidu or Google brain-related posture. AC will also be devoted to this issue in a later article.

At the same time, this issue has been fixed at the official 4.2 (API level 17), using @javascriptinterface annotations to declare addjavascriptinterface injection methods. That is, only methods that use @javascriptinterface are injected into the webview.

5, WebView Long press the pop-up actionmode menu style problem



Samsung phone webview Pop-up menu style There is a problem that may occur, the workaround can inherit the WebView override Startactionmode () method, and then modify the menu style.

@Override
Public Actionmode Startactionmode (Actionmode.callback Callback) {
Return Super.startactionmode (New Customcallback (GetContext (), callback));
}

public static class Customcallback implements Actionmode.callback {
Private Actionmode.callback Callback;
Private context context;

Public Customcallback (context context, Actionmode.callback Callback) {
This.callback = callback;
This.context = context;
}

@Override
public boolean Oncreateactionmode (actionmode mode, menu menu) {
return Callback.oncreateactionmode (mode, menu);
}

@Override
public boolean Onprepareactionmode (actionmode mode, menu menu) {
int size = Menu.size ();
for (int i = 0; i < size; i++) {
MenuItem MenuItem = Menu.getitem (i);
Final drawable moremenudrawable = Menuitem.geticon ();

if (moremenudrawable! = null) {

Menuitem.seticon (drawableutil.getthemedrawable (context, moremenudrawable));

}
}
return true;
}

@Override
public boolean onactionitemclicked (actionmode mode, MenuItem item) {
return callback.onactionitemclicked (mode, item);
}

@Override
public void Ondestroyactionmode (Actionmode mode) {
Callback.ondestroyactionmode (mode);
context = NULL;
}
}

Of course, if you don't need a long press event, you can register the long-press event for WebView

Mwebview.setonlongclicklistener (V, {
return true;
});

6. Hardware acceleration Issues

In general, using WebView development will use hardware acceleration to improve the rendering speed of webview. Can be set in the Androidmanifest.xml file

Android:hardwareaccelerated= "true"

can also be used in the page

View.setlayertype (view.layer_type_hardware, NULL);

However, simply using the two methods above, turn on hardware acceleration and do not turn on hardware acceleration on some phones will have a problem such as this or that, for example, if the hardware acceleration has been turned on, some phones may appear screen of the problem And WebView may still have crash problems in different manufacturers ' handsets. And Crash's problem is generally reported webview the bottom of the error. You can refer to the following processing methods:

Turn on hardware acceleration in onpagestart and turn off hardware acceleration in onpagefinish.

@Override
public void onpagestarted (WebView view, String URL, Bitmap favicon) {
if (getactivity () = = NULL | | getactivity (). isfinishing ()) {
Return
}
View.setlayertype (view.layer_type_hardware, NULL);
super.onpagestarted (view, URL, favicon);
}
@Override
public void onpagefinished (WebView view, String URL) {
if (getactivity () = = NULL | | getactivity (). isfinishing ()) {
Return
}
View.setlayertype (View.layer_type_none, NULL);
super.onpagefinished (view, URL);
}

7. Run WebView with independent process

Older drivers who have a certain experience with WebView may be able to extract the WebView module from the project and run it in a separate process. For example, use the attribute process in the manifest file to specify a separate process.

<!--Web Page--
<activity
Android:name= ". UI.CommonUI.Activity.WebBrowserActivity"
Android:configchanges= "Orientation|screensize|keyboardhidden"
Android:hardwareaccelerated= "true"
Android:label= ""
android:process= ": Web"
android:screenorientation= "Portrait"/>

This is done because WebView has a memory leak in the underlying implementation of the previous version, causing the page to close but still not freeing the memory, and the WebView module in the standalone process is a good solution to the problem, shutting down the process when the webview is turned off, This frees up the associated memory.

But with a multi-process architecture, inter-process data sharing is a problem. For example, process a sets cookies, and I also share this cookie in process B. The current solution that AC believes is feasible is to use ContentProvider to share data. This problem AC did not write the corresponding demo, hoping that the old driver can lead the way.

8. WebView Life Cycle Callback

WebView also have life-cycle callback methods that need to be recalled in the activity or fragment corresponding life methods. Mainly Onresume (), Onpasuse () and Ondestory () (or Ondestoryview ()) are the callback implementations of several methods.

 @Override 
public void Onresume () {
if (Mwebview! = null) {
mwebview.resumetimers ();
  & nbsp    mwebview.onresume ();
  &NBSP;}
Super.onresume ();
}

@Override
public void OnPause () {
if (Mwebview! = null) {
mwebview.pausetimers ();
&N Bsp      mwebview.onpause ();
  &NBSP;}
Super.onpause ();
}
@Override
public void Ondestroyview () {
if (Mwebview! = null) {
Mwebview.stoploading ();
((ViewGroup) mwebview.getparent ()). Removeview (Mwebview);
Mwebview.removeallviews ();
Mwebview.setwebchromeclient (NULL);
Mwebview.setwebviewclient (NULL);
Unregisterforcontextmenu (Mwebview);
Mwebview.destroy ();
}
Super.ondestroyview ();
}

The callbacks of these methods have the advantage of no harm and can well avoid the rollover. For example, WebView play sound after the page closed after the sound of the problem, WebView page to return to the other page after the display blank does not refresh the problem and so on.

The above is angrycode in the use of webview development process of the pit, the corresponding solution is purely empirical reference, because the use of the environment and capacity limitations, if the article appeared wrong, welcome the old driver message points out.

Android uses WebView to develop common pits

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.