The examples in this article describe the ways that Android and JavaScript invoke each other. Share to everyone for your reference, specific as follows:
The combination of HTML page and Java code is generally used in the case of the interface is often changed, you can speak HTML in the network, the software opened will access the network to obtain the latest interface. The disadvantage is that it can be affected by network signals, which leads to slow access.
1. Use WebView to display HTML code
2. Allow WebView to execute JavaScript
Copy Code code as follows:
Webview.getsettings (). Setjavascriptenabled (True);
3. Get to HTML file, also can get from network
Copy Code code as follows:
Webview.loadurl ("file:///android_asset/index.html"); HTML files are stored in the Assets folder
4. Add an object, so that JS can access the object's method, the object can also call the method in JS
Copy Code code as follows:
Webview.addjavascriptinterface (New Contact (), "Contacts");
The complete sample code is as follows:
Effect Chart:
Mainactivity
Import android.app.Activity;
Import android.content.Intent;
Import Android.net.Uri;
Import Android.os.Bundle;
Import Android.webkit.WebView;
public class Mainactivity extends activity {private WebView webview;
public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Load page WebView = (webview) Findviewbyid (R.id.webview);
Allows JavaScript to perform webview.getsettings (). Setjavascriptenabled (True);
Locate the HTML file, or use the file on the network Webview.loadurl ("file:///android_asset/index.html");
Add an object, so that JS can access the object's method, the object can call JS in the method Webview.addjavascriptinterface (new Contact (), "Contacts"); Private Final class Contact {//javascript calls this method to call the public void call (String phone) {startactivity (The new Intent (in Tent.
Action_call, Uri.parse ("Tel:" + phone)); //html call this method to pass data public void Showcontacts () {String json = "[{\ name\": \ "zxx\", \ "amount\": \ "9999999\", \ "Phone\"
: \ "18600012345\"}]; Call the method in JS Webview.loadurl ("JavAscript:show (' + JSON + ') ');
}
}
}
HTML:
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
You need to add permissions to call:
Copy Code code as follows:
<uses-permission android:name= "Android.permission.CALL_PHONE"/>
I hope this article will help you with the Android program.