Calling Android application code from WebView
UpdatedMy earlier blog post showed how an application can call WebView’s javascript functions from Java code. This time I’m going to show you how to call Java code from the WebView.
In order to call Java code from a WebView, you need to create a WebViewClient implementation. Basicly this means that you need to create a class that extends WebViewClient class and you need to set your WebView to use it. Below is a simple example of a custom WebViewClient implementation:
private class CustomWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.startsWith("korri://")) {
Toast.makeText(JSTestActivity.this, "Custom protocol found", Toast.LENGTH_LONG).show();
return true;
}
return false;
}
}
and this is how you set your WebView to use it:
WebView webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new CustomWebViewClient());
The CustomWebViewClient class overrides on method from WebViewClient, the shouldOverrideUrlLoading method. This method is where communication from WebView is interpreted. The method checks if an url starts with a custom protocol (korri://) and if does, it shows a Toast to the user. The custom protocol is used to distinct communication to the application from normal page navigation. In order to show the Toast, you need to add a link to the html file which is loaded to the WebView. This link has to start with the special protocol, for example like this:
<a href="korri://toast">Show toast!</a>
The example above is very simple and also easily extendable. You could for example create a link to korri://toast/Hello_World and show all text that follows after korri://toast/ in a Toast. This way you can modify the text shown to the user in the WebView.
Calling application methods from WebView doesn’t require anything else than this, it’s really this easy.
Word of warning though, calling Java code from WebView is always a slow operation. The reason for this is that the browser running in the WebView is native program and the application is running in a VM. So everytime you make a call, the operating system needs route the call from native code to VM. If you make a call here and there, you probably won’t notice any performance problems, but if you’re doing a lot of them, like ten or more every second, you will notice some slowness.
Update 9.8.2012:
I’ve written a tutorial which shows how to enable communication with WebView and Javascript. It contains both cases, calling javascript from application and calling application code from javascript, and it’s available at http://www.korri.net/tutorials/android/communication-to-and-from-android-webview-with-js.html.