Java and JavaScript interaction on WebView, webviewjavascript

Source: Internet
Author: User

Java and JavaScript interaction on WebView, webviewjavascript

In Android development, considering the development efficiency and interface updates, sometimes WebView can be used in combination with web page technology to quickly develop mobile applications iteratively. WebView loading resources is not slow, but it is slow if there are more resources. For images, css, js, and html resources, it takes about 10-200 ms. Generally, it takes less than 30 ms. However, WebView starts rendering only after all resources are loaded. Therefore, it is written using native js. Do not use too many frameworks such as jQuery to improve the user experience.

In hybrid development, Android native sdks are sometimes used, such as calling cameras, viewing albums, and recording. Therefore, JavaScript on the web page can be used to call Android SDK interfaces. Because Android WebView is based on the webkit kernel, it integrates the interface functions of js and java to facilitate development and use.

Interface layout xml:

1 <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" 2 xmlns: tools = "http://schemas.android.com/tools" 3 android: layout_width = "match_parent" 4 android: layout_height = "match_parent"> 5 6 <WebView 7 android: id = "@ + id/webView" 8 android: layout_width = "fill_parent" 9 android: layout_height = "fill_parent" 10 android: layout_above = "@ + id/linearLayout" 11/> 12 <LinearLayout 13 android: id = "@ + id/linearLayout" 14 android: layout_width = "match_parent" 15 android: layout_height = "wrap_content" 16 android: layout_alignParentBottom = "true" 17> 18 <Button19 android: id = "@ + id/btn" 20 android: layout_width = "wrap_content" 21 android: layout_height = "wrap_content" 22 android: text = "Java calls JavaScript interface" 23> 24 </Button> 25 </LinearLayout> 26 </RelativeLayout>

Java code:

1 private WebView webView; 2 private Handler handler = new Handler (); 3 private Button button; 4 @ SuppressLint ("SetJavaScriptEnabled") 5 @ Override 6 protected void onCreate (Bundle savedInstanceState) {7 super. onCreate (savedInstanceState); 8 setContentView (R. layout. activity_main); 9 webView = (WebView) findViewById (R. id. webView); 10 11 // customize webView settings 12 WebSettings webSettings = webView. getSettings (); 13 webSettings. setJavaScriptEnabled (true); 14 webView. addJavascriptInterface (new MyJavaScriptInterface (MainActivity. this), "javaInterface"); 15 // if it is commented out, the alert pop-up window in javaScript will expire and 16 webView will not be displayed. setWebChromeClient (new WebChromeClient (); 17 // webView. setWebChromeClient (new MyWebChromeClient (); 18 19 // test whether webView loading is normal 20 // webView. loadUrl ("http://www.baidu.com/"); 21 webView. setWebViewClient (new HelloWebView (); 22 webView. loadUrl ("file: // android_asset/index.html"); 23 24 button = (Button) findViewById (R. id. btn); 25 button. setOnClickListener (new View. onClickListener () {26 27 @ Override28 public void onClick (View v) {29 String param = "bb"; 30 webView. loadUrl ("javascript: showTitle ('" + param + "')"); 31} 32 }); 33} 34 35 private class HelloWebView extends WebViewClient {36 @ Override37 public boolean shouldOverrideUrlLoading (WebView view, String url) {38 // TODO Auto-generated method stub39 view. loadUrl (url); 40 return true; 41} 42} 43 44/** 45 * define the android interface that JavaScript can call in the main thread after 46 * @ author CHQ47 * API 17, every called java function must be declared @ JavascriptInterface48 */49 public class MyJavaScriptInterface {50 private Context context; 51 52 public MyJavaScriptInterface (Context context) {53 this. context = context; 54} 55 @ JavascriptInterface56 public String toString () {57 return "this is interface"; 58} 59 @ JavascriptInterface60 public void clickOnAndroid () {61 Toast. makeText (context, "js calls Android :.... ", Toast. LENGTH_SHORT ). show (); 62} 63/** 64 * Android calls the JS interface. To enable the subthread to call 65 */66 @ JavascriptInterface67 public void call () {68 Toast. makeText (context, "the android client calls the JavaScript interface again", Toast. LENGTH_SHORT ). show (); 69 handler. post (new Runnable () {70 @ Override71 public void run () {72 String param = "bb"; 73 webView. loadUrl ("javascript: showTitle ('" + param + "')"); 74} 75}); 76 77} 78 79}

Note: There are several changes in WebView descriptions on the Internet in the early days. 1) In Android 4.2 or a later version, WebView is used to implement interdebugging between Java and Js. the java interface must declare @ JavascriptInterface; 2) WebView must call setWebChromeClient () to adapt to Js and other pop-up windows; 3) when calling the JavaScript interface in the interface bound to addJavascriptInterface, you must enable the subthread to call the interface (error: Caused by: java. lang. throwable: A WebView method was called on thread 'javabridge '. all WebView methods must be called on the same thread .);

 

HTML code:

<Html> <script type = "text/javascript"> // Android-defined interface 1 function callAndroidInterface () {window. javaInterface. clickOnAndroid ();} // function showTitle (param) {alert ("parameter passing:" + param); var x = document. getElementById ("title"); alert ("title:" + x. innerHTML );} </script> <body> 

In the preceding html file, javaInterface is the name of the interface entry injected into the addJavacriptInterface () method in webView. With this name, you can directly call interfaces in Java. (This html page must be kept in the project assets directory and loaded by webView. loadUrl ("file: // android_asset/index.html );

 

:

In the dialog box that appears, the webpage with the URL "file: //" is displayed. If it is a web page on the server, the source IP address is displayed. This is obviously not what we want. In the next article, we can rewrite WebChromeClient to modify the optimization of webView such as dialog box and confirmation box.

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.