Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Using Native Handset Functionality from WebView via JavaScript

Author: Colin Wilcox -- Published? true -- FormatLanguage: W

Problem:

The advent of HTML5 as standard in many browsers means that applications can exploit the features of the HTML5 standard to create applications much more quickly than if they were written in native Java. This sounds great for many applications but alas not all of the cool functionality on the device is accessible through HTML5 and Javascript. Webkits attempt to bridge the gap but may not provide all the functionality needed in all cases.

Solution:

You can invoke Java code in response to Javascript events using a bridge between the JS and Java environments.

Discussion:

The idea is to tie up events within the Javascript embedded in an HTML5 webpage and handle the event on the Java side by calling native code.

The example below creates a button in HTML5 embedded in a webview which when clicked causes the contacts application to be invoked on the device through the Intent mechanism

import android.content.Context;
import android.content.Intent;
import android.util.Log;

Write some thin bridge code:

public class JavaScriptInterface
{
    private static final String TAG = "JavaScriptInterface";
    Context iContext = null;
	
    /** Instantiate the interface and set the context */
    JavaScriptInterface(Context aContext)
    {
        // save the local content for later use
        iContext = aContext;
    }

    public void launchContacts();
    {
         iContext.startActivity(contactIntent);
         launchNativeContactsApp ();
    }
}

The native code to actually launch contacts is below:

private void launchNativeContactsApp() 
{
    String packageName = "com.android.contacts";
    String className = ".DialtactsContactsEntryActivity";
    String action = "android.intent.action.MAIN";
    String category1 = "android.intent.category.LAUNCHER";
    String category2 = "android.intent.category.DEFAULT";

    Intent intent = new Intent();
    intent.setComponent(new ComponentName(packageName, packageName +       className));
    intent.setAction(action);
    intent.addCategory(category1);
    intent.addCategory(category2);
    startActivity(intent);
}

The Javascript which ties this all together is shown below. In this case the call is triggered by a click event

<input type="button" value="Say hello" onClick="showAndroidContacts())" />
<script type="text/javascript">
    function showAndroidContacts()
    {
         Android.launchContacts(); 
    }
</script>

The only preconditions is that the web browser has Javascript enabled and the interface is known. This is done by

WebView iWebView = (WebView) findViewById(R.id.webview);
iWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
No records found.