Android and JavaScript call each other
The combination of Html pages and Java code is generally used when the interface is often changed. You can talk about html in the network. Once the software is opened, it will access the network to obtain the latest interface. The disadvantage is that the access speed is slow due to the impact of network signals.
1. Use WebView to display HTML code
2. Allow WebView to execute JavaScript
WebView. getSettings (). setJavaScriptEnabled (true );
3. You can obtain HTML files from the network.
WebView. loadUrl (file: // android_asset/index.html); // The HTML file is stored in the assets folder.
4. Add an object so that JS can access the method of this object. This object can also call the method in JS.
WebView. addJavascriptInterface (new Contact (), contact );
The complete sample code is as follows:
:
MainActivity
[Java]
- 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 the page
- WebView = (WebView) findViewById (R. id. webView );
- // Allows JavaScript Execution
- WebView. getSettings (). setJavaScriptEnabled (true );
- // Find 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 method of the object. The object can call the method in JS.
- WebView. addJavascriptInterface (new Contact (), contact );
- }
-
- Private final class Contact {
- // Call this method using JavaScript
- Public void call (String phone ){
- StartActivity (new Intent (Intent. ACTION_CALL, Uri. parse (tel: + phone )));
- }
-
- // Html calls this method to pass data
- Public void showcontacts (){
- String json = [{ame: zxx, amount: 9999999, phone: 8600012345}];
- // Call methods in JS
- WebView. loadUrl (javascript: show ('+ json + '));
- }
- }
- }
HTML:
[Html]View plaincopy
Name |
Deposit |
Phone number |
-
-
-
-
-
- <Script type = text/javascript>
- Function show (jsondata ){
- Var jsonobjs = eval (jsondata );
- Var table = document. getElementById (personTable );
- For (var y = 0; 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 = + jsonobjs [y]. phone +;
- }
- }
- </Script>
-
-
-
-
-
-
-
-
-
-
To make a call, you must add the following permissions: