Android Development: JavaScript Bridge Example - Fully Explained!

In this smartphone generation, we expected have a full browser functionality in API; iOS SDK is coming with UIWebView and Android has WebView.

This means, developer is able to take advantage the core engine, such as JavaScript parser. This might make developer’s life easier sometime because we can reuse same libraries from JavaScript - e.g form + validations, drawing chart and so on.

I looked around android documentations, StackOverflow and some forums but I could not find a good summary and organized complete example. Here, I demonstrate my experiment of a full cycle of JavaScript / Java function calls from both sides.

Setup

1. Add WebView in your layout, and add HTML file in asset folder.




  1. Create a JavaScriptHandler class which has a reference to parent activity.
public class JavaScriptHandler {
    MyActivity parentActivity;
    public JavaScriptHandler(MyActivity activity) {
        parentActivity = activity;
    }

    public void setResult(int val){    
        this.parentActivity.javascriptCallFinished(val);
    }

    public void calcSomething(int x, int y){
        this.parentActivity.changeText("Result is : " + (x * y));
    }
}
  1. Load HTML and JavaScript in the Activity class and add the JavaScriptHandler class above.
myWebView = (WebView)this.findViewById(R.id.myWebView);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(new JavaScriptHandler(this), "MyHandler");
myWebView.loadUrl("file:///android_asset/index.html");

  1. Now, it’s ready to call from both side.

A) Call JavaScript from Java In step 3, we added the handler in the WebView, and “MyHandler” would be the object that you can call in the html as below:

window.MyHandler.myfunction();

B) Call JavaScript from Java

On the other hand, if you need to call JavaScript from Java side, we use loadUrl with javascript keyword as below:

myWebView.loadUrl("javascript:myjavascriptfunc()");

or you can directly manipulate something like:

myWebView.loadUrl("javascript:document.getElementById('test1').innerHTML = '<strong>"+someText+"</strong>'");

So how about the full cycle? What if I want to call JavaScript function from Java, then I would get the result back from the process?

Here is important key point: loadUrl function is asynchronous call. Let’s say, your Java function wants to call a JavaScript function via loadUrl. However, loadUrl dispatch the thread and you need to let WebView call your handler’s function inside. So let’s create two functions: call and finished.

Calling JavaScript

public void callJavaScriptFunctionAndGetResultBack(int val1, int val2){
    myWebView.loadUrl("javascript:window.MyHandler.setResult( addSomething("+val1+","+val2+") )");
}

Catching when the JavaScript call finished

public void javascriptCallFinished(int val){
    Toast.makeText(this, "Callback got val: " + val, 5).show();
}

In this example, I’m passing two integer values in the first call function. In the argument, it’ll call addSomething() JavaScript function, and then it places the result back by calling MyHandler’s function, which is an interface object, in order to call Java function over there. Let’s come back to Java side. In Java side, since we get reference from the parent Activity class, we just call one of member functions.

public class JavaScriptHandler {
//....
    public void setResult(int val){
        this.parentActivity.javascriptCallFinished(val);
    }
//....

Here is the function to be called in Activity.

public void javascriptCallFinished(int val){
     Log.v("mylog","MyActivity.javascriptCallFinished is called : " + val);
}

… however this would not give a good result when you write a real app because you often put the value back to UI which need to be run in the main thread!

So use a runOnUiThread (such a nice name). If you need to pass something, you must add final keyword, which allows the variable to be used inline Runnable class.

Finally, the “Finished” function will be look like this:

public void javascriptCallFinished(final int val){
    Log.v("mylog","MyActivity.javascriptCallFinished is called : " + val);
    // I need to run set operation of UI on the main thread.
    // therefore, the above parameter "val" must be final
    runOnUiThread(new Runnable() {
        public void run() {
            myResult.setText("Callback got val: " + val);
        }
    });
}

Below is the diagram how it goes from Java to JavaScript and from JavaScript to Java.

That’s it! This could be confusing in the first look, so please download the sample code. The project is created with IntelliJ and this is 100 times better IDE than eclipse.

Download

https://github.com/kiichi/AndroidJavasScript

Demo

Reference

Most of information were published on those documentation pages: http://developer.android.com/guide/webapps/webview.html http://developer.android.com/resources/articles/using-webviews.html

By: kiichi on: