Binding JavaScript with Android Native technique where WebView allows to bind Android code using an interface.
addJavaScriptInterface() method should be used which passed the class that provides the JS interface and
WebView allows you to bind JavaScript code to Android code through an interface for JS
The name that will be used to display the instance in JS e.g. AndroidFunction and as a result an interface called AndroidFunction for JavaScript running in WebView will be created dynamically.
From JavaScript calls Java Sample Code
For example, Below is described a class with methods that you want to execute in JS:
public class JavaScriptInterface {
Context myContext;
JavaScriptInterface(Context c) {
myContext = c;
}
@JavascriptInterface
public void showMessage(String message) {
Toast.makeText(myContext, message, Toast.LENGTH_SHORT).show();
}
}
Installing this interface in WebView can be done with the following code sample
webView.addJavascriptInterface(new JavaScriptInterface(this), "AndroidFunction");
Now to interact with java code in JavaScript, you can use the interface name as below
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function initMessage()
{
var message = 'Hello Java World!'
AndroidFunction.showMessage(message);
}
</script>
</head>
<body>
<div>
<input type="button" value="Send Message" name="submit"
id="btnSubmit" onclick="javascript:return initMessage();" />
</div>
</body>
</html>
Hope the above example will be helping in getting and understanding the communication from JavaScript calls Java Method.
Now let’s understand the other way around where call JavaScript function from Java
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Javascript :</h1>
<div id="msg">0</div>
<script>
function increaseVolume() {
var volumeMsg = document.getElementById("msg");
volumeMsg.innerText = parseInt(volumeMsg.innerText) + 10;
}
</script>
</body>
</html>
Then next Java class you need to add a call to the loadUrl() method, into the parameters of which we need to pass the name of the method declared in JavaScript.
webWidgetView.loadUrl("javascript:increment()");
Hope this will be helping in integrating Android Native and Web-based interfaces smartly.