Wednesday, 1 April 2015

Html page and Android App Interaction


Simple Webview controls like html buttons etc interaction with Android app . This Post shows how to create a interface between the andriod app and webview using javascript.

In this post we will be calling method from android i.e placed javascript of html file And Method in android app from javascript in Html File.


1. MainActivity.java


public class MainActivity extends ActionBarActivity {

WebView webview;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview=(WebView)findViewById(R.id.webview);  
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new WebAppInterface(this), "Android");      
webview.loadUrl("file:///android_asset/example.html");
btn=(Button)findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {

webview.loadUrl("javascript:showAndroidToastTwo(\"Calling From Android\")");
}
});
}
}



2. WebAppInterface.java

import android.content.Context;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

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();
    }

}




XML Layouts :

1. activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.htmlclick.MainActivity" >

<Button 
    android:id="@+id/btn"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="Click Javascript"
    />
    <WebView
        android:id="@+id/webview"
        android:layout_below="@+id/btn"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>



Html File To be placed in html for testing goes like this :

1. example.html

<html>
<head>
<script type="text/javascript">
    function showAndroidToast(toast) {
        Android.showToast(toast);
    }
 function showAndroidToastTwo(toast) {
        Android.showToast(toast);
    }
</script>
</head>
<body>
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
</body>



Output : 











No comments:

Post a Comment