Getting Started with an Android Widget Populated with Javascript and Apache Cordova

This is the forth part of a tutorial demonstrating the ability to re-use JavaScript in many different environments. The first part dealt with the creation of the re-usable service, a simple command line wrapper which called the service as well as a simple test which checks the service is performing as expected. The second part of the tutorial discussed the development of a simple web application based on that service, using browserify to wrap the service so that it will run in any modern browser. The third part took the web app, and showed you how to use Apache Cordova, a platform independent JavaScript mobile phone development framework, to make your simple app run on modern smartphones.

This fourth part of the tutorial assumes that you have understood the concepts so far raised in earlier parts of the tutorial.

Project Set-up

You can continue to use the old directory containing the files from the previous tutorial, but I recommend you create yourself an new project environment like this:

Create a new directory mkdir crprice or md crprice or whatever your operating system supports and cd to it. Then use the following:

Price Service

The price service is exactly the same as in the previous examples. Interestingly although the environment will be different - instead of running in a nodejs server environment, the application will be running in the sandboxed environment of the mobile phone, nevertheless we can still use exactly the same code, even to access network resources, by using the tool browserify. This not only resolves code that has been required through npm modules, but also provides a wrapper which allows the developer to access services that nodejs would provide natively through the browser instead.

Below the full source code of the service. Just copy and paste this and save with a name price-service.js

Remember to use gulp vs to build the web app files. You’ll need to do this at least once before moving on to the next part of the tutorial

A Native Java Class to Populate the widget

You’ll notice in the config.xml file a reference to a plugin cordova-plugin-ace. This is a plugin written by some Microsoft employees which facilitate building native UI apps with cordova. Sadly, as of December 2016, this project is no-longer maintained by Microsoft, but in the spirit of open source, they invite you to fork it.

Taking advantage of ace, its necessary to create only a very simple java class to interface with the javascript and populate the widget. The source is here below:

Copy and paste this and save with a name native/android/src/net/log1/apps/priceApp/ListWidgetProvider.java