Android Activity
package com.example.myapp;
import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;
public class WebViewActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webView = new WebView(this);
setContentView(webView);
/*
* Note the label Android, this is used in the Javascript side of things
* You can of course change this.
*/
webView.addJavascriptInterface(new JavascriptHandler(), "Android");
webView.loadUrl("http://example.com");
}
}
Java Javascript Handler
import android.webkit.JavascriptInterface;
public class JavascriptHandler {
/**
* Key point here is the annotation @JavascriptInterface
*
*/
@JavascriptInterface
public void jsCallback() {
// Do something
}
@JavascriptInterface
public void jsCallbackTwo(String dummyData) {
// Do something
}
}
Web Page, Javascript call
<script>
...
Android.jsCallback();
...
Android.jsCallback('hello test');
...
</script>
Extra Tip
Passing in a complex data structure, a possible solution is use JSON.
Android.jsCallback('{ "fake-var" : "fake-value", "fake-array" : [0,1,2] }');
On the Android side use your favorite JSON parser ie: JSONObject