Android: Java and JavaScript Interfacing in Android Webview


points:

# do not run on android emulator 2.3.x. there is a severe bug and so far not resolved. run on android sdk api >= 8
# put the index.html file in assets folder
# click on javaButton will change the background color of the webView by calling a Js function
# click on the link on webView will change the text of the javaButton
# for debugging purpose: console.log() in js can be viewed on android logcat by implementing onConsoleMessage(ConsoleMessage cm)

index.html


<html>
<script type="text/javascript">
    function changeBackgroundColor() {
        console.log('Inside changeBackgroundColor');
        if ( document.body.style.background == 'red' ) {
            document.body.style.background = 'blue';
        } else {
            document.body.style.background = 'red';
        }
    }
</script>
    <body>
    <a onClick="window.JsInterface.onClickJavascriptButton()"> Click me, i am JS Button </a>
    </body>
</html>

main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <Button android:id="@+id/bt_javaButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/buttonText"
            android:padding="5dp"
            android:onClick="onClickJavaButton"/>

    <WebView
            android:id="@+id/wv_main"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

</LinearLayout>

string.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Js-Java, Interfacing</string>
    <string name="buttonText">This is a Java Button</string>
    <string name="buttonText2">I am clicked from JS</string>

</resources>

MyActivity.java


package com.example;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.webkit.*;
import android.widget.Button;


public class MyActivity extends Activity
{
    private static final String TAG = MyActivity.class.getSimpleName();

    private Button mJavaButton;
    private WebView mWebView;
    private Handler mHandler;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);

        mHandler = new Handler();

        mJavaButton = (Button) findViewById(R.id.bt_javaButton);
        mWebView = (WebView) findViewById(R.id.wv_main);

        // Enabling JS
        mWebView.getSettings().setJavaScriptEnabled(true);

        // Java and Javascript interfacing
        mWebView.addJavascriptInterface(new JavascriptInterface(), "JsInterface");

        // for debugging, this will handle the console.log() in javascript
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(ConsoleMessage cm) {
                Log.d(TAG, cm.message() + " #" + cm.lineNumber() + " --" + cm.sourceId() );
                return true;
            }
        });

        mWebView.loadUrl("file:///android_asset/index.html");
    }

    public void onClickJavaButton (View mView) {
        mWebView.loadUrl("javascript:changeBackgroundColor()");
    }

    class JavascriptInterface {

        JavascriptInterface() {}

        public void onClickJavascriptButton() {
            Log.d(TAG, "onClickJavascriptButton entered");
            mHandler.post(new Runnable() {
                public void run() {
                    Log.d(TAG, "onClickJavascriptButton inside run");
                    if (mJavaButton.getText().toString().compareTo(getResources().getString(R.string.buttonText)) == 0)
                        mJavaButton.setText(R.string.buttonText2);
                    else 
                        mJavaButton.setText(R.string.buttonText);
                }
            });
        }
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s