Android webview Loading native HTML and implementing Java and JS interaction

Source: Internet
Author: User

In a recent project, using a custom map to convert a custom map to an HTML page, what you need to do now is to load the native HTML into Android and interact with it.

Related explanation:

In fact, webview loading resources is not slow, but if there are more resources, of course, is very slow. Pictures, CSS, JS, html each of these resources probably need to 10-200ms, generally 30ms is OK. However, WebView is necessary to wait until all the resources are loaded before rendering, so the speed of loading is very important! From Google we learned that WebView loading the page order is: First load the HTML, and then parse from the inside of the CSS, JS files and the image resources on the page to load. If the WebKit cache is inside, it is not loaded. After these resources are loaded, CSS rendering and JS execution are performed. CSS rendering generally does not take a long time, dozens of milliseconds is OK. The key is the execution of JS, if used jquery, it takes 5-6 seconds to execute. And during this time, if not set the background in the WebView, the webpage part is white, it is very difficult to see. This is a very bad user experience. Therefore, if you use the Web layout program, it is best not to use those large JS framework. It is best to use native JS write business scripts to increase loading speed and improve user experience.

How to implement Java and JS interaction on Android?

Android WebView is based on the WebKit kernel, webview integration of JS and Java Intermodulation interface functions, through the Addjavas Criptinterface method, you can register Java class into WebKit, To the Web page JS call, but also through the Loadurl method to WebKit pass a URL, for the browser to parse, Java and JS to achieve the interaction.

To run the JS script on the Web page, WebView must be set to support Javas Cript.

Java code: 1mwebview.getsettings (). Setjavascriptenabled (True);

Then set the page to load WebView:

Web page: Webview.loadurl ("http://www.google.com");

Local page: Webview.loadurl ("file:///android_asset/XX.html"); Local storage in: Assets folder

WebView after the basic initialization we have to give it, add a callback to the proxy class javascriptinterface, and give it a call name: NCP

Java code: 1mwebview.addjavas criptinterface (New Javas criptinterface (), "NCP");

Javas Criptinterface can be a common Java class, class implementation methods, can be JS callback:

Java code:

Final class Javas Criptinterface {

public int Callonjs () {

return 1000;

}

public void CallOnJs2 (String mode) {

Todo

}

}

Java to invoke the method of JS, just know the method name JS can:

Java code: 1mwebview.loadurl ("Javas cript:onsavecallback ()");

JS here is more simple:

JS Code:

Window.onload = function () {

document.getElementById (' btn_1 '). AddEventListener (' Click ', Onbtnclick, false);

var _int_value = Window.ncp.callOnJs ();

Alert ("Get int from Java:" + _int_value);

}

function Onbtnclick () {

WINDOW.NCP.CALLONJS2 ("click");

}

Java and JS interactions have the following features:

1.Java Call JS inside the function, the speed is not satisfactory, about one hundred or two hundred milliseconds at a time, if you want to do a very interactive thing, this speed will make people crazy. And the reverse is not the same, JS to tune the Java method, fast, basically 40-50 milliseconds at a time. So try to use JS to call the Java method, rather than Java to invoke the JS function.

2.Java Call JS function, no return value, and JS call Java method, can have a return value. The return value can be a base type, a string, or an object. If it's a string, there's a nasty question, and 3rd I'll talk about. If it is an object, the object will be converted to a JS object, which can be accessed directly inside the method. But I do not recommend that Java be returned to JS is the object, unless it is necessary. Because JS receives objects returned by Java, there are some swap objects, and if the number of these objects increases to 500 or more than 600, the program will have problems. So try to return the base data type or string.

3.Js call Java method, the return value if it is a string, you will find that the string is native, you can not make some modifications to it, such as want to substr it, not to be taken. How to fix it? Turn into locale. You can use the toLocaleString () function. However, this function is not fast enough, and it can be time-consuming to convert many strings.

Here is a specific example:

1. Create a new Assets folder and copy the local HTML page to the folder.

2.xml file

<relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"Tools:context=". Mainactivity "> <TextView Android:id= "@+id/tv"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "@string/hello_world"/> <WebView Android:layout_below= "@+id/tv"Android:id= "@+id/webview"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"/> </RelativeLayout>

3.java file

 PackageCom.example.webview_workflowy; Importandroid.app.Activity; Importandroid.content.Intent; ImportAndroid.net.Uri; ImportAndroid.os.Bundle; ImportAndroid.webkit.WebView; ImportAndroid.widget.Toast;  Public classMainactivityextendsActivity {PrivateWebView WebView;  Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);          Setcontentview (R.layout.activity_main); //Load PageWebView =(WebView) Findviewbyid (R.id.webview); //allow JavaScript to executeWebview.getsettings (). setjavascriptenabled (true); //Locate the HTML file or use the file on the networkWebview.loadurl ("file:///android_asset/index.html"); //add an object that allows JS to access the object's method, which can invoke the method in JSWebview.addjavascriptinterface (NewContact (), "contact"); }        Private Final classContact {//JavaScript calls this method to make a phone call         Public voidCall (String phone) {//startactivity (New Intent (Intent.action_call, Uri.parse ("Tel:" + phone)); Toast.maketext (mainactivity. This, Phone, Toast.length_long). Show (); }            //HTML calls this method to pass data         Public voidshowcontacts () {String json= "[{\" name\ ": \" zxx\ ", \" amount\ ": \" 9999999\ ", \" phone\ ": \" 18600012345\ "}]"; //invoking the method in JSWebview.loadurl ("Javascript:show ('" + JSON + "')"); }                     Public voidToast (String str) {toast.maketext (mainactivity. This, "AAAAAAAAAAAA---" +str, toast.length_long). Show (); }      }    }  

4.html

<!      DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > function Show (jsondata) {var jsonobjs=eval (jsondata); var table= document.getElementById ("persontable");  for(var y=0; y<jsonobjs.length; y++) {var tr=Table.insertrow (table.rows.length); var td1= Tr.insertcell (0); var td2= Tr.insertcell (1); Td2.align= "Center"; var td3= Tr.insertcell (2); Td3.align= "Center"; Td1.innerhtml=Jsonobjs[y].name; Td2.innerhtml=Jsonobjs[y].amount; Td3.innerhtml= "<a href= ' Javascript:contact.call (\" "+ jsonobjs[y].phone+" \ ") ' >" + jsonobjs[y].phone+ "</a>"; }              }          </script> 

Android webview Loading native HTML and implementing Java and JS interaction

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.