I bumped into application which is an webview application where some of the native functionality has been exposed to webview. I wanted to learn how to do it by recreating it by myself. The code is pretty much copied from this Google tutorial.
Add network permission to
<uses-permission android:name="android.permission.INTERNET" />
Add the webview
I created the project with Android Studio and used Basic Activity as the main activity so the file to add the webview is
<WebView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" />
Load some page in the webview
I want to get something visible as soon as possible so let’s load http://rapidprogrammer.com
WebView myWebView = (WebView) findViewById(R.id.webview); myWebView.loadUrl("http://rapidprogrammer.com");
And the screen should look something like this (btw: see this oneliner to take a screenshot).
Don’t forget to enable JS in the webview.
Prepare the backend
I decided to serve HTML and JS to webview from Python Bottle. The server is self-explanatory and a bit out of the scope of this post so I won’t go into details with that. The point is that it doesn’t matter how the files get into the webview as long as they are fed into the webview somehow.
Add the class to webview with
Android. The object name comes from the
showToast(String toast). The if statement is there to check if the object is set. With this if statement the site can be used from other browsers as well where the Android interface doesn’t exist.
Update the URL to your server
Update your IP address to webview, for example
Complete source code in Github.