WebView JavaScript interacts with native code

Source: Internet
Author: User
Tags gettext

http://my.oschina.net/u/1376187/blog/172296

The project uses the WebView Display Web page, which requires Web pages and native methods to interact, to search for an article, to forward sharing:

=============================================================================================================== ===============

Reprint please indicate the source is very handsome mobile development column http://blog.csdn.net/wangtingshuai/article/details/8631835 in the development process of Android, there are many times need to use the local Java generation Code to interact with JavaScript. Android on the interaction is very good encapsulation, in the development we can easily use Java code to call WebView in the JS, you can also use JS in the WebView to invoke the local Java code, so that we can achieve a lot of the original function, For example, click on the phone number on the page, the phone automatically dial the phone, click on the Web joke, automatically send text messages and so on. Needless to say, the goal of this tutorial is as follows
    1. Java code in Android calls WebView inside the JS script
    2. The JS script in WebView calls the local Java code
    3. Java calls JS and passes parameters
    4. JS calls Java and passes parameters
Function one Android call WebView in the JS script is very convenient, only need to call WebView Loadurl method (note to turn on JS support)

[HTML] View plain copy
    1. Enable JavaScript
    2. Contentwebview.getsettings (). Setjavascriptenabled (True);
    3. Loading HTML from the assets directory
    4. Contentwebview.loadurl ("file:///android_asset/wst.html");
    5. No parameter calls
    6. Contentwebview.loadurl ("Javascript:javacalljs ()");
function two
WebView JS calls The local Java method, this feature is slightly cumbersome to implement, but it is not very complicated, first to WebView binding Javascriptinterface,js script through this interface to invoke Java code. [Java] View plain copy
    1. Contentwebview.addjavascriptinterface (This, "WST");
Javainterface is actually a common Java class, which is the Java code we implement locally, passing object to WebView and assigning an alias, so that the JS script can call our method through the alias we give, in the code above, This is an instantiated object, WST is the alias of this object in JS

Function three
Java code calls JS and passes parameters
Only need to use the JS function to add parameters, the following is the case of passing a parameter, the need for a number of parameters of the time of their own stitching and line, note that the STR type in the pass time parameters to be enclosed in single quotation marks

[Java] View plain copy
    1. Mwebview.loadurl ("Javascript:test ('" + aa+ "')"); AA is the parameter of the JS function test ()
Function Four
JS call Java functions and pass parameters, Java function Normal writing, in the JS script when called a little attention
Then in the HTML page, the following code can be used to implement the call [HTML] view plain copy
    1. <div id= ' B ' ><a onclick= "window.wst.clickOnAndroid (2)" >b.c</a></div>

Here is an example of the implementation of the above function here is the HTML code of the instance, loaded from the Assert, when the original project, the Chinese web page loaded from the Assert will appear garbled, the solution is to assign HTML encoding. As follows
[HTML] View plain copy
  1. <meta http-equiv= "Content-type" content= "text/html;charset=gb2312" >
  2. <script type= "Text/javascript" >
  3. function Javacalljs () {
  4. document.getElementById ("Content"). InnerHTML + =
  5. "<br\>java called the JS function";
  6. }
  7. function Javacalljswithargs (ARG) {
  8. document.getElementById ("Content"). InnerHTML + =
  9. ("<br\>" +arg);
  10. }
  11. </script>
  12. <body>
  13. This is my HTML <br/>
  14. <a onclick= "window.wst.startFunction ()" > Click Invoke Java Code </a><br/>
  15. <a onclick= "window.wst.startFunction (' Hello World ')" > Click Invoke Java code and pass parameters </a>
  16. <br/>
  17. <div id= "Content" > Display </div>
  18. </body>

The Java code is as follows

[Java] View plain copy
  1. Package Wst.webview;
  2. Import Android.annotation.SuppressLint;
  3. Import android.app.Activity;
  4. Import Android.os.Bundle;
  5. Import Android.view.View;
  6. Import Android.view.View.OnClickListener;
  7. Import Android.webkit.WebView;
  8. Import Android.widget.Button;
  9. Import Android.widget.TextView;
  10. Import Android.widget.Toast;
  11. public class Mainactivity extends Activity {
  12. Private WebView Contentwebview = null;
  13. Private TextView Msgview = null;
  14. @SuppressLint ("setjavascriptenabled")
  15. @Override
  16. public void OnCreate (Bundle savedinstancestate) {
  17. Super.oncreate (savedinstancestate);
  18. Setcontentview (R.layout.main);
  19. Contentwebview = (WebView) Findviewbyid (R.id.webview);
  20. Msgview = (TextView) Findviewbyid (r.id.msg);
  21. Enable JavaScript
  22. Contentwebview.getsettings (). Setjavascriptenabled (True);
  23. Loading HTML from the assets directory
  24. Contentwebview.loadurl ("file:///android_asset/wst.html");
  25. Button button = (button) Findviewbyid (R.id.button);
  26. Button.setonclicklistener (Btnclicklistener);
  27. Contentwebview.addjavascriptinterface (This, "WST");
  28. }
  29. Onclicklistener Btnclicklistener = new Button.onclicklistener () {
  30. public void OnClick (View v) {
  31. No parameter calls
  32. Contentwebview.loadurl ("Javascript:javacalljs ()");
  33. Passing parameter calls
  34. Contentwebview.loadurl ("Javascript:javacalljswithargs" ("+" ' Hello World ' "+") ");
  35. }
  36. };
  37. public void Startfunction () {
  38. Toast.maketext (This, "JS called the Java function", Toast.length_short). Show ();
  39. Runonuithread (New Runnable () {
  40. @Override
  41. public void Run () {
  42. Msgview.settext (Msgview.gettext () + "\njs called the Java function");
  43. }
  44. });
  45. }
  46. public void Startfunction (final String str) {
  47. Toast.maketext (this, str, toast.length_short). Show ();
  48. Runonuithread (New Runnable () {
  49. @Override
  50. public void Run () {
  51. Msgview.settext (Msgview.gettext () + "\njs called the Java function pass parameter:" + str);
  52. }
  53. });
  54. }
  55. }

layout file [HTML] view plain copy
  1. <?xml version= "1.0" encoding= "Utf-8"?>
  2. <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
  3. Android:layout_width= "Fill_parent"
  4. android:layout_height= "Fill_parent"
  5. android:orientation= "Vertical" >
  6. <webview
  7. Android:id= "@+id/webview"
  8. Android:layout_width= "Fill_parent"
  9. android:layout_height= "Fill_parent"
  10. android:layout_weight= "9"/>
  11. <scrollview
  12. Android:id= "@+id/scrollview1"
  13. Android:layout_width= "Fill_parent"
  14. android:layout_height= "Wrap_content" >
  15. <textview
  16. Android:id= "@+id/msg"
  17. Android:layout_width= "Fill_parent"
  18. android:layout_height= "Fill_parent"
  19. android:text= "Text"/>
  20. </ScrollView>
  21. <button
  22. Android:id= "@+id/button"
  23. Android:layout_width= "Fill_parent"
  24. android:layout_height= "Wrap_content"
  25. android:layout_weight= "1"
  26. Android:text= "Java Call js function"/>
  27. </LinearLayout>

I hope we have some help. resources

http://download.csdn.net/download/wangtingshuai/5106571

=============================================================================================================== =====

Concluding a few sentences:

1, WebView Load Web page, native code can interact with JS in the Web page and pass parameters (a parameter).

2, JS call native code that part of a sudden may not see very clear, here to tidy up:

?
12345678910111213141516171819202122 //native code方面//使用addJavascriptInterface绑定“wst”contentWebView.addJavascriptInterface(this, "wst");//添加需要响应的方法,注意必须为publicpublicvoidstartFunction(final String str) {          Toast.makeText(this"js调用了java函数", Toast.LENGTH_SHORT).show();          runOnUiThread(newRunnable() {                @Override            publicvoidrun() {                  msgView.setText(msgView.getText() + "\njs调用了java函数");                }          });      }//js方面<a onClick="window.wst.startFunction(‘hello world‘)" >点击调用java代码并传递参数</a><span><span style="line-height:20px;"> </span></span>
Share to:

WebView JavaScript interacts with native code

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.