Can HTML5 access native components

I have a question. Can an HTML5 page interact with native components in android?

What i am trying to achieve is that on a HTML5 page that displays a list of content. i want to create a notification that some content has arrived.?

Im guessing, a way to do this is to use a webview and display my HTML5 content there but how to do get callback from the webview so that i can notify a user that some content has arrived via notifications bar that can be access using native android coding?

I already know how to create notifications on android and how to create a webview, i just need to find a way to send data from html5 page to a android component and possibly vice versa.

Can this be achievable or too ambitious?

Answers


Yes, you can achieve this via a JavaScript Interface. Via this the JavaScript can call functions defined in the interface you attach.

http://developer.android.com/guide/webapps/webview.html

In your Activity:

WebAppInterface mInterface;

public void onCreate() {
    mInterface = new WebAppInterface(this);
    mWebView.addJavascriptInterface(mInterface, "MyAndroidInterface")
}

Now define an object where the calls will go to:

public class WebAppInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}

Now in Javascript you can do:

MyAndroidInterface.showToast("hello world");

The way back (from native to Javascript) you can do via Javascript injection. Define function in Javascript:

function helloBack(param) {
} 

Now you can call mWebView.loadUrl("javascript:helloBack(hi);");


Need Your Help

EXC_BAD_ACESS when buying an in app purchase, only after going into the store the second time

crash in-app-purchase exc-bad-access payment

Okay. I have in-app purchases working i my application. I have a view controller that acts as the store of my application, and the user can buy things from it.

Smart Stack + Docker

architecture cloud docker

I am working on a proof of concept project using Smart Stack (from airbnb) and Docker to build distributed service cloud.