An interesting approach in building Android native apps can be achieve through the use a WebView that will execute HTML and JavaScript code: by setting the WebView to fill the screen and using a local HTML page that contains our JavaScript code, we get the ability to develop entire apps based on JavaScript!
Another great feature is the ability to register an interface class that can be invoked from the JavaScript code and which is implemented inside the native app, hence providing to our script the full potential of Android OS. The only limitation at the moment is that WebView doesn’t support WebGL, however it seems that it can be worked around by relying on a technology named CocoonJS, something to investigate in a future post…
The approach is greatly inspired from Android documentation that you can find here.
Below is the code that allows to load an html page stored in my app assets. In order to make the sample a bit more interesting, I decided to use a previous post I published on JavaScript: Js.CAD
public class MainActivity extends Activity
{
WebAppInterface _interface;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Js.CAD for Android");
WebView webView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
_interface = new WebAppInterface(this);
webView.addJavascriptInterface(
_interface,
"WebAppInterface");
webView.loadUrl("file:///android_asset/jscad.html");
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class WebAppInterface
{
Context _context;
/** Instantiate the interface and set the context */
WebAppInterface(Context context) {
_context = context;
}
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String msg)
{
Toast.makeText(_context, msg, Toast.LENGTH_SHORT).show();
}
}
}
With just a couple a cosmetic modifications, I was able to port the app to my device in no time!
Android users will now be able to use that cutting edge application, that lets you create not only lines but also circles and all this with the colors of your choice… Enjoy!
Full Eclipse Project available for download below:
Comments