Sunday, June 8, 2014

Calling Javascript from Android Java coding

In Android application, WebView is the component for display web pages. As Hybrid application are popular now, there are needs of calling javascript method from Android Java coding. We can do this by implement the addJavascriptInterface method in WebView.

The following example demonstarte this:
Step 1: Create a new Android project "JavascriptDemo" in Eclipse. A html web page is created in the assests directory.

Step 2: Modify activity_javascript_demo.xml layout document. Add a button in the WebView

<LinearLayout xmlns:android="" 
        android:text="Hello World!!" 
        android:text="Change the webview content" 

Step 3: Create a demo.html file under assest directory.

    <script language="javascript"><!-- 
 function fillContent(){ 
     document.getElementById("content").innerHTML =  
   "This Content is showed by Android invoked Javascript function."
// --></script>   
    <p><a onClick="window.demo.startMap()" href="">Start GoogleMap</a></p> 
    <p id="content"></p> 
    <p>Javscript Demo ---- Android and Javascript interaction</p> 

Step 4: Modify
package com.easyinfogeek.javascriptdemo;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
public class JavascriptDemo extends Activity {
  private WebView mWebView;  
     private Button mButton;  
     public void onCreate(Bundle savedInstanceState) {  
     private void setupViews() {  
         mWebView = (WebView) findViewById(;  
         WebSettings mWebSettings = mWebView.getSettings();  
         mWebView.addJavascriptInterface(new Object() {  
             public void startMap() {  
                 Intent mIntent = new Intent();  
                 ComponentName component = new ComponentName(  
         }, "demo");  
         mButton = (Button) findViewById(;  
         mButton.setOnClickListener(new Button.OnClickListener() {  
             public void onClick(View v) {  

No comments:

Post a Comment