Saturday, October 27, 2012

Add Native Support to JS in Android HTML5 Apps

Running HTML 5 apps in Android , is not effective as you loss a lot of native power , Android provides the ability to expose native power to JS so you can use the powerful native support in your app.

Here is the simple steps:

1. Create any class and name it any thing like JavaScriptInterface

public class JavaScriptInterface {
        Context mContext;

        JavaScriptInterface(Context c) {
            mContext = c;

        public void doSomething() {
         System.err.println("inside do something");

2. The class should have constructor that take Context as parameter

3. During instatiation send the activity object in the constructor and add nick(prefix) name to be used inside JS to call this class methods:

     webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");


    public void onCreate(Bundle savedInstanceState) {
    WebView webView=(WebView)findViewById(;
    webView.setWebChromeClient(new WebChromeClient());
    //remove this line for emulator bug in Android 2.3
    webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
       //the following line to prevent the backlight from going during application running.

4. In the JS call this methods


You can see in the console the outcome of the sys err statement.
(Android is the prefix we have specified during creating instance of this JS interface)

5. Of course we can have many interfaces each for specific purpose.

Simple and straightforward but there is a bug in android emulator in 2.3 so better to test it on mobile devices direct in case you need to test it on such platform.

No comments:

Post a Comment