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
Example:


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");


Example:

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_crazy);
    WebView webView=(WebView)findViewById(R.id.webView);
    webView.setWebChromeClient(new WebChromeClient());
    webView.getSettings().setJavaScriptEnabled(true); 
    webView.getSettings().setDatabaseEnabled(true);
    webView.getSettings().setDatabasePath("/data/data/osa.ora.test/databases/");
    webView.getSettings().setDomStorageEnabled(true);
    //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.
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    webView.loadUrl("file:///android_asset/www/index.html");    
    }


4. In the JS call this methods

Example:
Android.doSomething();

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