Monday, 12 October 2015

Call Java function from JavaScript over Android WebView


     Here I am going to explain how to call a java function from webview


                                                      
Step 1)MainActivity .java

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends Activity {
WebView webView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Activity MyActivity = this;
webView= (WebView) findViewById(R.id.webview);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {

MyActivity .setTitle("Loading...");
MyActivity .setProgress(progress * 100);

if (progress == 100)
MyActivity .setTitle("Android Dhina");
}
});
webView.setWebViewClient(new WebViewClient());
webView.addJavascriptInterface(new WebAppInterface(this), "Android");

webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/web.html");

}

public class WebAppInterface {

Context context;

WebAppInterface(Context c) {
context= c;
}

public void showToast(String toast) {
Toast.makeText(contexttoast, Toast.LENGTH_SHORT).show();
}

}

}

Step 2)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">

    <WebView
        android:id="@+id/webview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>


Step 3)assets/web.html

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width; user-scalable=0;" />
<title>Android Dhina</title>

<h1>Android Dhina Webview</h1>
</head>
<body>
<input type="button" value="Call Function"
onClick="showAndroidToast('Hello Dhina!')" />

<script language="javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
 }
</script>

</body>
</html>


Happy Coding :)