Getting Started with Java and JavaScript interactions in Android

Source: Internet
Author: User

How to implement JavaScript and Java interaction

It is very convenient to implement Java and JS interaction. This usually takes only a few steps.

    • WebView Open JavaScript Script execution
    • WebView sets the interface for JavaScript calls.
    • The client and the Web side write code that calls each other.

#直接看示例代码:

The Java code is as follows:

Package Com.ccb.javascript;import Java.net.urisyntaxexception;import Android.annotation.suppresslint;import Android.annotation.targetapi;import Android.app.activity;import Android.content.intent;import Android.os.Build; Import Android.os.bundle;import Android.util.log;import Android.webkit.javascriptinterface;import Android.webkit.webchromeclient;import Android.webkit.websettings;import Android.webkit.webview;import Android.webkit.webviewclient;import android.widget.Toast; @TargetApi (build.version_codes. Donut) public class Javascriptdemo extends Activity {private static final String LogTag = "mainactivity"; @SuppressLint ("Ja Vascriptinterface ") @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate) ; Setcontentview (R.layout.javascriptdemo); final WebView Mywebview = (WebView) Findviewbyid (R.id.mywebview); WebSettings settings = Mywebview.getsettings (); settings.setjavascriptenabled (true); Mywebview.addjavascriptinterface (New Jsinteration (), "control"); MyWebView.setwebchromeclient (New Webchromeclient () {}); Mywebview.setwebviewclient (new Webviewclient () {@Overridepublic void onpagefinished (WebView view, String URL) {super.onpagefinished (view, URL); TestMethod (Mywebview);}}); Mywebview.loadurl ("file:///android_asset/js_java_interaction.html");} private void TestMethod (WebView WebView) {String call = ' Javascript:sayhello () '; call = "Javascript:alertmessage (\" "+" Co Ntent "+" \ ")", call = "Javascript:toastmessage (\" "+" content "+" \ ")", call = "Javascript:sumtojava"; Webview.loadurl (call);} public class Jsinteration {@JavascriptInterfacepublic Intent toastmessage (String message) {Toast.maketext ( Getapplicationcontext (), message, Toast.length_long). Show (); Intent Intent = null;//Parse Intent URI into Intent objectin T flags = 0;boolean Isintenturi = false;if (Message.startswith ("intent:")) {Isintenturi = True;flags = intent.uri_intent_s Cheme;} else if (Message.startswith ("#Intent;")) {Isintenturi = true;} if (Isintenturi) {try {intent = Intent.parsEuri (message, flags);} catch (URISyntaxException e) {e.printstacktrace ();}} StartActivity (intent); return intent;} @JavascriptInterfacepublic void Onsumresult (int result) {log.i (LogTag, "Onsumresult result=" + result);}}}

  

Front page code

  

Call Example JS call Java

Call Format Window.jsInterfaceName.methodName (parametervalues) In this example we are using control as the injected interface name.

Specific invocation:

<a onclick= "Window.control.toastMessage (' #Intent; component=com.ccb.javascript/ Com.ccb.javascript.mainactivity;end ') "href=" ";> invoke Methods in Java </a>

(' #Intent; Component=com.ccb.javascript/com.ccb.javascript.mainactivity;end ')  is to pass a intent that opens the activity. It can also be a string or other.

  

Java Call JS

WebView the basic format for invoking JS is Webview.loadurl ("Javascript:methodname (parametervalues)")

Call js no parameter no return value function
String call = "Javascript:sayhello ()"; Webview.loadurl (call);

  

Call JS with parameter no return value function

Note that you need to escape double quotation marks for a string as a parameter value.

String call = "Javascript:alertmessage (\" "+" content "+" \ ")", Webview.loadurl (call);

  

Call JS a function with parameters that have a return value

Android before 4.4 did not provide a direct call to the JS function and get the value of the method, so before, the usual idea is the Java call JS method, the JS method executes, call Java code again to return the value.

1.Java Calling JS code

String call = "Javascript:sumtojava", Webview.loadurl (call);

  

2.js function processing and returns the result by calling the Java method

function Sumtojava (Number1, number2) {       Window.control.onSumResult (number1 + number2)}

  

3.Java get the JS function return value in callback method

@JavascriptInterfacepublic void Onsumresult (int result) {  log.i (LogTag, "Onsumresult result=" + result);}

  

4.4 Processing

You can use Evaluatejavascript after Android 4.4. Here is a simple interactive example of a JS method with a return value

function Getgreetings () {      return 1;} Java code calls private void Testevaluatejavascript (WebView WebView) with the Evaluatejavascript method {  Webview.evaluatejavascript ("Getgreetings ()", New Valuecallback<string> () {  @Override public  Void Onreceivevalue (String value) {      log.i (LogTag, "Onreceivevalue value=" + value);}}  ); Output: I/mainactivity (1432): Onreceivevalue value=1 Note that the result returned is a string, for a simple type will attempt to convert to a string return, for complex data types, It is recommended that JSON be returned as a string. The Evaluatejavascript method must be called on the UI thread (the main thread), so Onreceivevalue is also executed on the main thread.

  

Questions and Answersalert does not eject

You should be not set webchromeclient, follow the code below to set

Mywebview.setwebchromeclient (New Webchromeclient () {});

  

uncaught referenceerror:functionname is not defined

The problem occurs because the JS code of the webpage is not loaded , and the JS method is called. The workaround is to call the JS method after the Web page is loaded

Mywebview.setwebviewclient (New Webviewclient () {  @Override public  void onpagefinished (WebView view, String URL) {      super.onpagefinished (view, URL);      Execute the JS function you want to invoke here  }  });

  

uncaught Typeerror:object [Object Object] has no methodSecurity Restriction issues

If there is a problem with a machine with more than 4.2 versions, then the system is in a security limit. Android documentation so to speak

Caution:if you ' ve set your targetsdkversion to + or higher, you must add the @JavascriptInterface annotation to any meth OD that you want available your Web page code (the method must also is public). If you don't provide the annotation, then the method won't accessible by your Web page when running on Android 4.2 or Higher.

Chinese to the effect of

Warning: If your program target platform is 17 or higher, you must add a @javascriptinterface comment to the method that is exposed to the Web page callable (this method must be public). If you do not do this, the Web page will not be able to access your method in 4.2 on a later platform.

Workaround
    • Set Targetsdkversion to 17 or higher to introduce @javascriptinterface annotations
    • Create yourself a comment interface named @javascriptinterface, and then introduce it. Note that this interface cannot be confused. This method is not recommended, probably after the 4.4 problem.

Note, create @javascriptinterface code

Public @interface Javascriptinterface {}

  

Code obfuscation issues

If the version that is not confused runs normally, after the garbled version of the code runs the error and prompts uncaught Typeerror:object [Object Object] has no method, that is you did not do obfuscation exception handling. Adding code like this in a confusing file

Keepattributes *annotation*keepattributes Javascriptinterface-keep class com.example.javajsinteractiondemo$ jsinteration {    *;}

  

All WebView methods must is called on the same thread filter logs have found this problem.

  

E/strictmode (1546): Java.lang.throwable:a WebView method was called on thread ' Javabridge '. All WebView methods must is called on the same thread. (Expected Looper Looper (Main, Tid 1) {528712d4} called on Looper (Javabridge, tid 121) {52b6678c}, FYI main Looper is Loo Per (main, Tid 1) {528712d4}) E/strictmode (1546): at Android.webkit.WebView.checkThread (webview.java:2063) e/ Strictmode (1546): at Android.webkit.WebView.loadUrl (webview.java:794) E/strictmode (1546): at com.xxx.xxxx.xxxx.xxxx . Xxxxxxx$javascriptinterface.oncangobackresult (xxxx.java:96) E/strictmode (1546): at Com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce (Native Method) E/strictmode (1546): at Com.android.org.chromium.base.SystemMessageHandler.handleMessage (systemmessagehandler.java:27) E/strictmode ( 1546): at Android.os.Handler.dispatchMessage (handler.java:102) E/strictmode (1546): at Android.os.Looper.loop ( looper.java:136) E/strictmode (1546): at Android.os.HandlerThread.run (handlerthrEAD.JAVA:61) 

  

The Java callback thread after the JS call is not the primary thread. such as print logs can be verified

Threadinfo=thread[webviewcorethread,5,main]

To resolve the above exception, place the WebView operation in the main thread.

Webview.post (New Runnable () {    @Override public    void Run () {        webview.loadurl (your_url)    });

  

Transferred from: Http://droidyue.com/blog/2014/09/20/interaction-between-java-and-javascript-in-android/

Getting Started with Java and JavaScript interactions in Android

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.