Embedding a Cordova WebView in a Native Android app

Sept 2013 – Updated to use cordova 2.9 – see github repo

A few months ago I wrote a tutorial on Hybrid apps and accessing native functions from an Android WebView. I made a comment that while Apache’s Cordova can do this fine, you wouldn’t use Cordova from within an app. Then I discovered you could embed a Cordova WebView within a native app. If you’re not familiar with Cordova, this means you can create an Activity within your native app which uses HTML5 and JavaScript to create the UI and access native functions and features via the Cordova API.

Here is an example of the finished product. The image on the left is a bog-standard native Android activity with a button that kicks off the Cordova Activity. The image on the right is an Activity that uses an embedded Cordova WebView.
Image of Basic ActivityImage of Cordova Activity

How do you do this? You can follow a post on the PhoneGap site here, but this probably won’t result in a working application, unless you know a bit of Android development. There is a more informative tutorial by Joe Bowser (he wrote PhoneGap for Android) on his site here.

The Joe Bowser tutorial has a related github repository for a bigger project that could be easy to get lost in if you are new to various aspects of Cordova/Android. What I have done is put up a simple project on github that has just the two Activities you see in the images above. If I was to offer some general steps in starting a project of your own, it would go something like this;

  • Create your new Android Project with a main Activity
  • Create a FrameLayout to hold the CordovaWevView (example)
  • Create a new sub-class of Activity (for your ‘CordovaActivity’)
  • Add the cordova.jar to your libs folder and then include this in Java Build Path > Libraries. You should see something like this…
  • Java Build Path

  • Now you can add an import to org.apache.cordova.api.CordovaInterface in your ‘CordovaActivity’ and let this class implement CordovaInterface
  • When you implement this interface’s methods, you are best to either follow the Joe Bowser tutorial, or take a look at my github project (specifically this file) if you run into any problems.
  • Once this Activity is working and you can move back an forth between your native and Cordova Activities, you can head over to your assets file and start working on your HTML/JS/CSS3 files as you would in a normal Cordova project

I’m going to leave it there as I have spent a lot of time this weekend studying and I don’t want to end up like this:

To get the source code for this project, head over to https://github.com/Linnesq. If you have any questions, thoughts or found this useful please leave a comment below. There will be some tutorials on Robotium and using SQLite on Android coming next/soon. Adios!