This article is part of in the series
Last Updated: Thursday 12th December 2013

Webviews make it easy to use web technologies to build graphical user interfaces for native applications. Many people already know some webcraft, and it's easy to pick up and well worth knowing, so there's a broad appeal in being able to use these technologies for native apps. This also allows developers to tap into the vast and thriving ecosystem of JavaScript libraries that have gone supernova since HTML5 started rolling out.

To use webviews, you'll obviously need to know some HTML, CSS and JavaScript, so basic familiarity with these languages is assumed in this article.

Webviews with SL4A: A Call and Two Hooks

When you first use webviews, you'll find things work a bit differently than you'd expect coming from programming native graphical interfaces or programming web applications. Thankfully, things are much easier all round. For example, you don't have to manage frame rates or buffers in your event loop as webviews are rendered by an engine, in SL4A's case, WebKit, so the Python code doesn't need to handle any of that. At the same time, you don't have things like AJAX and websockets to manage; you just post simple events to and from the user interface. In many ways, you have the best of both worlds with webviews.

This is one of those things that's easier to explain with some code, so we'll just start with a hello-world and keep incrementing.

To build a webview based app, you need at least one HTML file and one Python script, which implement the view and an app to use it. For simplicity, we'll call them index.html and main.py.

The Webview Call

Below is the content of index.html. The meta tag in the head is just there to tell the device not to try and rescale anything.

This is the content of main.py:

This script creates an Android object, called droid, which is standard procedure for SL4A apps ~ droid exposes the Scripting Layer API. The script then launches the webview using the droid's webViewShow method, passing a local file URL as the only argument. Obviously, you need to edit that URL to point to your HTML file. The script then sleeps for 4 seconds, just so you have time to see the webview on your device before the Python script exits and kills it.

As you can see, launching a webview just takes a single call. To keep the program running indefinitely, and to manage communication between the Python script and the webview, the script will need an event loop, but there's a couple of hooks you need to know about first.

The First Hook

Once you have your webview running, you need to pass messages to it and handle messages from it. Everything boils down to events.

Apart from the Android stuff, the following version of index.html is pretty basic. There's an explanation of how it all works below.

Now, index.html has a textual banner at the top of the page, with a text field underneath that the user can type into. When the user enters some text, the string in the text field is passed to a function, postInput, which posts the string to the Python script as an event, using the Droid's eventPost method. The first argument to eventPost, 'line', is currently irrelevant and could've been anything.

This was a good point to chuck in some simple CSS too, else the text field would have been really small and ugly.

Below is a new version of main.py. This version will launch the webview, then block and wait for an event. When it gets the event, it grabs the data, the string the user entered in the text field, and uses the Android Text to Speech Facade to read out the user input. It exits immediately afterwards, so it will only handle one event.

It's easy to put the last three lines in a loop to handle multiple events, but it's worth looking at the code a bit more first.

SL4A Webview Example Screenshot: Simple Echo Version

Line 6 assigns droid.eventWait().result to a variable, event. The eventWait method is blocking, it just waits for any event to be posted, then returns a dict that contains information about the event.

Note that all calls to the the Scripting Layer are RPC calls and communication is in JSON. It's the incoming JSON that's always returned, as a dict, by any call to the SL4A API. This is covered in detail elsewhere, but, in short, it's the result that's often all you care about, hence it's commonplace to see API calls written like the one on Line 6.

Anyway, droid.eventWait().result, and therefore event in the script above, is a dict containing information about the event.

If the last three lines of main.py were inside a loop, it could handle multiple events, but then there'd be no way for the user to exit the app cleanly.

The following version of main.py can handle two types of event, line and kill events. The line events will be handled as before; the script just reads a line of user input out loud, but this time, this will happen inside a loop, iterating until a kill event occurs. A kill event will cause the script to exit, taking the webview with it.

The webview itself doesn't currently have any way to post kill events, but that's easily resolved later.

Note that the script references event['name'] and event['data']. The following JavaScript snippet just illustrates how events are posted from the front end. The call takes two arguments, both strings. The first is an event name, the second is some event data.

The arguments are passed into main.py as a dict, which it assigns to event. The first argument is available as event['name'], the second as event['data'].

The following version of index.html includes a little more HTML and CSS, adding a button that will post a kill event when it is pressed.

The app now has a webview that can post multiple types of event, distinguished by name, that carry data about the event to handler code in the Python event loop. Now that you understand how to post events 'inward', from JavaScript to Python, you just need to know how to post events 'outward', from Python to JavaScript. Then you have all the bits you need to do graphical user interfaces with webviews in SL4A.

The Second Hook

Posting an event from Python is really easy, especially if you know how it's done in JavaScript. Basically, you just use the same API in the same way, with droid.eventPost('name', 'data'). Handling events in JavaScript is a little different though. JavaScript is event oriented, so the event loop is implicit. To handle events in JavaScript, you need to register callbacks. In this case, you register functions to handle events by name, using droid.registerCallback('name' some_function).

The following JavaScript snippet registers a simple callback, using a lambda, for handling spam events.

Note that the function receives one argument, e, which is the event. It has all the properties you should now expect from an event object.

SL4A Webview: Complete Example

This final version of the example code implements a crude Python evaluator. It simply evaluates any Python expression the user enters and prints the result in the webview.

Doing this only requires a few small changes to index.html: In the body, there's an empty div with an id named output, which is where the output of the evaluation will appear, and, in the style sheet, there's a few simple tweaks for this output div. The only other change is to the JavaScript, where a callback is registered that will handle stdout events. The function just prints the event data to the output div, overwriting whatever might have been there before.

On the Python side, the only change is in how line events are handled. Now, a function called line_handler takes the line, evaluates it, converts the result to a string and then passes the string to the webview as the data for a sdtout event.

SL4A Webview Example Screenshot

Admittedly, this isn't the most exciting or polished app in the world, but it does illustrate how the Events API can be used with webviews to create graphical user interfaces. You could use the code module to turn this example app into a Python interactive interpreter without too much work, or use ACE to build a code editor that's better than the crappy SL4A built in one, or just replace the SL4A interface entirely.

There's a ton of good JavaScript libraries available now days for building front-ends. With Python on Android underneath, you can get really creative.

Obviously, it's all a bit of a hack, but it's a nice one. For a dev who just needs to modify some phones, or a hobbyist wanting to put out a tablet RPG, really for anyone who just wants an nice easy way to do a graphical app on an Android device, webviews are ideal.

Note: The Events API is a little richer and a lot more powerful than this example demonstrates, but the call to webViewShow and the two hooks, posting events from JavaScript to the Python event loop and from Python to JavaScript callbacks, are all you need to build a webview based user interface.

Note: Remember, you're still building a regular SL4A application, so you can use all the native Android UI components, like dialogues, toasts, notifications and so on, alongside webviews, giving you a nice and simple tool set for building rich Android applications with Python and HTML5.

About The Author