Wednesday, 18 April 2018

How to show Admob ads in an Apache Cordova app on Android

Since the demise of AdWhirl and my previous post about how to set up ads with Cordova, I've had to revisit it and get it working with AdMob which now uses Google Play Services.  Again there are very few instructions around for this, though I did find this useful looking Cordova plugin which seems to offer a neat solution which is likely easier than the solution I'm about to propose and is cross-platform where I am only working with Android.  However, for various reasons, I don't want to use the Cordova tools, I want to do it manually.  If you're like me then here is how to do it

This How-To uses a mash of the Cordova official documentation on WebViews, my previous post on AdWhirl and the Admob Quick Start guide.  The premise here is that, since Cordova can be made to display in an Android WebView, and AdMob also uses WebViews, we can combine the two and display one in front of the other

I'll assume you have an AdMob account and know how to create an Android app in your favourite IDE (I will be using Eclipse with ADT), or have an existing Android app running Cordova that you want to add Admob to

1. Set up Cordova to use a WebView

This largely follows the official Cordova WebView documentation with some small differences.  If you haven't set up your Android app to use Cordova yet you can follow much of the above tutorial which will create a simple Android app that uses Cordova WebViews

I found that the instructions for the Activity were slightly incorrect, so I've modified it slightly to not use the Config static object, but load the page like this


I have called my view CordovaView instead of TutorialView

    android:layout_height="match_parent"  />

2. Add AdMob to your app

Add Google Play Services

AdMob is no longer a downloadable SDK but instead uses Google Play Services.  Firstly you need to add this to your Android app.  There are instructions for different IDEs on this Android Developer Page.  This will allow you to use Google Play Services in your app

From here you can largely follow the Admob quick start guide but I will take you through the steps here

Modify your AndroidManifest.xml 

There are some AndroidManifest.xml changes you need to make to enable Google Play Services

You need to add some meta data to the <application>

<meta-data android:name=""
        android:value="@integer/google_play_services_version" />

and also add an activity

        <activity android:name=""
            android:theme="@android:style/Theme.Translucent" />

Also add these permissions

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Modify your file

You need to add Google Play Services to your file (in the root of your app) by adding the line


Add an ad fragment view

Following the quick start guide, create a new layout called fragment_ad.xml in res/layout to define how the ad will be displayed as follows

<RelativeLayout xmlns:android=""



You also need to create the banner_ad_unit_id referenced here in your values/strings.xml.  This will be your admob unit ID, but you can use the test one for now which displays a dummy ad (don't forget to replace it with your real unit ID before you go live)

<string name="banner_ad_unit_id">ca-app-pub-3940256099942544/6300978111</string>

Create an Activity for the ad view

You need to create an activity for the view in order to load the advert

public class AdFragment extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_ad, container, false);

    public void onActivityCreated(Bundle bundle) {
        int googlePlayServicesStatus = GooglePlayServicesUtil.isGooglePlayServicesAvailable(MyApplication.getAppContext());
        // if google play services is available
        if (googlePlayServicesStatus == ConnectionResult.SUCCESS) {
        // load the ad
       AdView mAdView = (AdView) getView().findViewById(;
       AdRequest adRequest = new AdRequest.Builder().build();
        // else do nothing

There are a few things to note there:
  • the fragment_ad layout name in the onCreateView() method needs to match the view name you created in the layout.  If you called it fragment_ad as in my example, you're all set
  • We reference GooglePlayServicesUtil in order to ascertain if Google Play Services is loaded on the device.  If it isn't, or you are using an emulator, you will get an exception.  Annoyingly this gives the user control over whether they receive ads since, with a rooted phone or one running a custom ROM, they may not have it installed.  If anyone has a solution to this, I'm keen to hear it
  • We do nothing if we can't connect to Google Play Services since we can't load the adverts using it
  • I needed a way of accessing the Context object.  I found an answer for this at Stack Overflow which involved creating a class for accessing the Context in a static way.  I've replicated the answer below
import android.content.Context;

public class MyApplication extends Application {

    private static Context context;

    public void onCreate(){
        MyApplication.context = getApplicationContext();

    public static Context getAppContext() {
        return MyApplication.context;

and add to the AndroidManifest.xml under the <application> tag


3. Link Cordova and AdMob WebViews

We now need to link the web views we have created in order to get them both to diplay

We need to do 3 things here:

Alter the layout type

We need to alter the layout type in res/layout/main.xml from the default LinearLayout to RelativeLayout.  Don't forget the closing tag :)

Display the ad view

We need to add a fragment child view of the main view in order to retain space for the advert.  This is separate to the Google Play Services ad fragment we already created which is the fragment for the advert itself.  We need a fragment in our main view in which to display the Google fragment

        android:layout_alignParentBottom="true" />

The should relate to the Activity class you created for displaying the ad fragment.  I called mine AdFragment.  

The alignParentBottom tells the layout manager that we want the fragment to be displayed at the bottom of the parent layout, this can be changed if you wish to display it elsewhere.  You can alignParentTop if you wish, or anywhere else from the RelativeLayout API

Add the ad view as a child of the main view

Finally we need to add the fragment as a child of the main view by adding this line to the main view, which I called CordovaWebView


Your final main.xml should resemble the following

<RelativeLayout xmlns:android=""
    android:orientation="vertical" >
    android:layout_above="@+id/adFragment" />
        android:layout_alignParentBottom="true" />

And you're done!

If you now run your app you should display an ad from AdMob where you specified

Don't forget to use your real AdMob ID when you deploy your app to Google Play

Monday, 8 August 2016

Adding Multiple Google Accounts to Kindle Fire

I recently bought a Kindle Fire because they are great value for an Android tablet and I knew they were ways of installing Google Play so I could access the apps I had already purchased through Google Play without having to repurchase them from Amazon. Specifically I wanted Minecraft for my son to play - honestly, for my son ;-)

The Fire I bought was the 5th Gen Kindle Fire (not HD, I wanted inexpensive!) and the awesome instructions on How To Geek worked perfectly at installing Google Play. I highly recommend this solution for installing it, it was simple to follow and easy to do. From here I was able to log in to Google Play and download my apps including Minecraft which I had previously paid for on another device

If all you want from this is to install apps from Google Play using your account, you are all set! However, if, like me, you also want to add a second Google user (in my case, my son) so he can use his account to synchronise his games, I got a bit stuck.  Unlike an Android tablet, there is no 'Accounts' option in the settings to add new Google accounts. The installation above does install the Google Accounts app, which is used to store account details, but there doesn't seem to be a way to access it directly. Google Play also doesn't have the option to add a 2nd account and relies on those already added

The solution, it turns out, is really simple. Simply install another Google app that requires an account (such as GMail). When you start the app, it will ask you to associate it with a Google account.

You can now add a different account and it will get added to your accounts on your Fire. You can verify this by opening Google Play and you should see that both accounts are now selectable. So if, like me, you want to use your own account but also want someone to be able to use their account for synchronising games, you can :)

Saturday, 31 January 2015

How to manually add Cordova plugins to your app

I have recently been trying to add a plugin to an existing Cordova app (using Cordova 3.7.0).  Since I didn't create my app using the CLI I had 2 options:

  1. Create a new app using the CLI and copy my source files over
  2. Add the plugin files to my existing app

For some reason I don't really like the idea of the CLI and wanted to do do this manually into an existing Android app, using Cordova, rather than use the CLI.  Don't ask me why, I just like doing things manually so I know what's going on under-the-hood I guess

If you are like me and want to add a plugin manually, this is how to do it.  These instructions, though written for Android, will work for any any supported platform.  I will call out any differences between platforms that I know of

Get the plugin source files

You need the source code files for your platform (so .java for Android, .m .h for iPhone etc) as well as the plugin javascript files.  You might be able to get the source files from the internet but if not you need the CLI anyway so get them.  Also if you've never set up your app for plugins before you need a cordova file called cordova_plugins.js

Install the Cordova CLI

Follow the Cordova instructions on how to install the CLI up to the point of having a working cordova command.  You need git and node.js installed

Create a dummy app

Create an app, it doesn't really matter what you call it, we're just using it to create the source files we need so we can copy them.  I've called mine hello after the instructions in the above tutorial

  cordova create hello com.example.hello HelloWorld

This will create a cordova app in a hello directory

Change into the created directory

  cd hello

I don't think you need to add platforms if you're not using the CLI to build the apps.  It doesn't do any harm though so run the command(s) if you want to

Edit: Note you will need to do this if you have never used a plugin in your app before as there is a source file you'll need to copy.  If you are adding Android then Cordova insists on you having Android-19 SDK installed

  cordova platform add android (or whatever platform you want)

At this point you have created your dummy app and can add your plugin(s)

Download the plugin source files

You need the name of the plugin you want to download, which can be obtained from the official Plugin API pages.  The one I wanted was the Network Information plugin, so this is the example I will use.  Replace the name with the one you want

Using the CLI, still in the dummy hello directory, install the plugin

  cordova plugin add

This will install the plugin source files you need.

Copy the source files into your app

The source file you want (eg .java for Android) are in the plugins/<plugin-package>/src/<platform> directory of the dummy app.  Copy this to the source directory of your app.  The file will be in an apache package, so either you need to create that package, or change the source file package declaration

In my case I placed the file in an org.apache.cordova.networkinformation package file

Copy the javascript files

The plugin javascript files you want will be in the plugins/<plugin-package>/www/ directory.  You need to create a new directory in the assets/www/plugins directory of your app with the same package name eg

If you've never used a plugin in your app before you also need a javascript source file.  You need to add a platform to do this, so do that as above.  Then copy the platforms/android/assets/www/cordova_plugins.js file to your assets/www directory in your app

Also note that you must call the original (not the plugins one you just copied) cordova javascript file cordova.js.  I had it called cordova-3.7.0.js and it didn't like it

You don't need to link any of these .js files to your .html page, they will be picked up automatically provided you have cordova.js linked, which you should have anyway if you are using cordova

Add entry to config.xml

You need to add an entry to your Cordova config.xml file found at res/xml/config.xml

You can copy it from the dummy app at platforms/<platform>/res/xml

In my case the entry looks like

    <feature name="NetworkStatus">
        <param name="android-package" value="org.apache.cordova.networkinformation.NetworkManager" />

And you're done

That's it, the plugin should now be available for use.  You can use the instructions from the plugin API page as normal.  Have fun :)

Wednesday, 28 January 2015

Manual upgrade of Apache Cordova for Android (2.9.0 to 3.7.0)

I hadn't upgraded Cordova for ages and was still on version 2.4.0 (now at 3.7.0 at the time of writing). so I was surprised, but mostly dismayed, that I now had to use the Cordova tools to create apps.  Maybe it is just me but I liked being able to copy the jar, javascript file and config into an Android app myself.  I did have a go at using the tool, but the npm still didn't create the jar I wanted and I'd be forever tied into using the tool.  So I spent some time working out how to upgrade manually, and this is how to do it.  

This obviously relies on you having java and android installed, which I'd guess you have if you're upgrading an Android app

Step 1

Download the latest zip file from and unzip it.

Step 2 

Install android if necessary and add it to the OS path.  You need ANDROID_HOME set or the android executable on the path.  I added both.

Make sure you have Android version 19 installed from Android's SDK manager

Step 3

Install ant and add it to the OS path so that ant can be executed from the command line

Step 4

Using a command line tool (cmd or bash, or whatever) change directory (cd) to the where you unzipped the cordova zip and cd into the package/framework directory

Run the following command

ant jar

If you get the error message that you need to create '' run the following command first (then run ant jar)

android update project -p .

This will create the jar file called cordova-<version>.jar

Step 5

Copy these files from the unzipped cordova directory into your Android app directory structure:
  • the created .jar file to your /libs directory (will be in the framework directory where you created it)
  • cordova.js from the assets directory in the zip file to your app assets directory
That's all I needed to do.  The settings all worked as before and now I've upgraded.  I hope this helps someone and it isn't just me that doesn't want to have to use the Cordova tools :)

Thursday, 28 March 2013

Mobilize.js versus responsive web design (RWD)

Mobilize.js versus responsive web design (RWD)

Both mobilize.js and responsive web design offer solutions to having a mobile and desktop site from the same codebase.  This is a comparison and evaluation of the 2 approches

mobilize.js rendering
I previously blogged about mobilize.js and how it can be used to transform a website dynamically between a desktop and mobile-enabled site.  As a brief background, mobilize.js is a javascript library that detects if a mobile browser is being used and, using client-side javascript, and re-renders the page using predefined
mobile-optimised css.  However mobilize.js is no longer being developed - the developers now recommend using responsive web design instead.  In one of the comments to my original post I said I would check out the relative merits and report back - this is me reporting back

Responsive web design works by detecting the size of the display and rendering differently using css (css3) media queries.  The screen size can be set in the css (or different css files loaded) - this means that for small-screen devices a mobile-optimised css can be used, for larger screens a different css.  There can be multiple configurations for different sizes and configurations. The css for that configuration is the one that is loaded and therefore the site rendered using that css.  I found a really useful guide which formed the basis for my approach

responsive web design rendering
Since I had already transformed my own website using mobilize.js, I thought the best indicator of the approaches would be to transform the same website using responsive web design.  As it turned out the results and approach were very similar - I simply adapted the css I'd created for the mobilize.js solution to render the small screen size using responsive web design.  As you can see, the results are very similar

I was pleasantly surprised at how easy it was to adapt the site to use responsive web design, so I tried another one I'd created for Becky Whittaker Counselling.  This one was much more complicated - mostly, I feel, due to it being static-width whereas mine was elastic-width. However since a mobile css needs to be created in both cases, the resulting css would likely be the same for both approaches.  I did make a schoolboy error whilst doing this which is that I forgot about the viewport.  This is IMPORTANT as I discovered when I had weird varying results due to the viewport on any given devices
<meta name="viewport" content="width=device-width">


Before responsive web design
Attempting both approaches has led me to believe that they have their relative merits which I've grouped into 4 categories:

  •  Configurations
    • What types of configurations are available?
    • How many configurations can you create?
  •  How is the page rendered?
  •  Which technologies are used?
  •  How flexible is it for changing the page?


Configuration Type
After responsive web design

mobilize.js uses the brower's user agent to recognise if the page should be rendered as a mobile site or not - if a mobile user agent for example
Mozilla/5.0 (Linux; U; Android 4.0.3; en-gb; HTC Sensation Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30
is detected then mobilize.js kicks in and renders the page using the mobile css.  This essentially means that a 10 inch tablet will render the same as 2 inch mobile phone

RWD uses resolution (in effect, screen size) to optimise the page regardless of what is being used, so a tablet with a larger resolution may render differently to a small mobile phone screen.  The user agent is ignored. This may mean that a large resolution phone renders the desktop site or that a small resolution netbook renders the mobile site

It might be that what you really want isn't to optimise for screen size but for touchscreen devices.  In this case mobilize.js might work, but there are probably better solutions for this particular case

Number of Configurations

mobilise.js has only 2 basic configurations - desktop or mobile.  As described above this is decided by the user agent

RWD has as many configurations as the creator decides - I don't know why you'd want to
but you could have hundreds if you wished. I've gone for 2 to most emulate what I did with mobilise.js
<link rel="stylesheet" type="text/css" media="screen and (max-device-width: 767px)" href="" />

<link rel="stylesheet" type="text/css" media="screen and (min-device-width: 768px)" href="stylesheet.css" />
which cuts over to the desktop site at a width of 768 pixels.  However you could have a smaller one for really small screens for example, or a tablet sized one etc

I feel that RWD has the edge here - the idea behind mobile sites is to optimise them for smaller screens rather than being for mobile phones per se.  If you want to alter content based on user agent there are javascript libraries for that already (see for an example).  It also may mean that the javascript needs updating occasionally as user agents change

Edge: RWD


mobilize.js essentially loads the page, including the javascript which detects the browser and re-renders it using the mobile css if required.  This means that the page is potentially rendered twice including downloading content, such as images, which may not be required for the mobile site

RWD renders the page based on the required css which means it is only rendered once and only with the content required by the page and css.  So if the mobile css doesn't specify an image usually used in the desktop css it won't be loaded

Edge: RWD

Technology stack

mobilize.js utilises (according to the creator) HTML5 and javascript. This makes it heavier weight than RWD. There might be an occasion when this choice is forced due to the lack of CSS3, but realistically I can't see many occasions when HTML5 is available and not CSS3

RWD uses HTML5 and CSS3 making it lighter weight than mobilize.js since no javascript is required.  I'd also argue that performance is better since it doesn't rely on loading and running javascript nor re-rendering the page

Edge: RWD

Flexibility of design

As mobilize.js relies on you specifying the location of existing <div> tags it is pretty easy to reorder them and apply new styles.  This means that, if I so choose, I could display the footer <div> at the top or whatever as the page will be re-rendered.  This provides a lot of flexibility for creating a page that is optimised for small screens

RWD relies on the current markup and how flexibly this has been created. There is potentially limited flexibility on optimising the page.  For example if my desktop site has a side menu I might be able to alter the CSS styles to display it at the top - or then again I might not since the existing markup might prevent that.  This is probably possible with some less-intensive javascript, though I haven't tried it

Edge: mobilize.js


It is important to note that in both of the cases I tried I have been adapting an existing desktop site to render nicely on mobile devices.  If I were designing a new site I would certainly go with responsive web design and design it accordingly.  I feel this is more in the spirit of designing mobile sites which isn't specifically to create a site for mobile devices but to optimise for the screen size

For an existing site mobilize.js has some advantages that may make you consider it, especially the ability to reorder the page.  I think your choice depends on how easy it is to adapt your website to be responsive - if it isn't possible then mobilize.js may provide your answer

Wednesday, 27 February 2013

Launch a website as a mobile app using PhoneGap/Apache Cordova

How to launch a website as a mobile app using PhoneGap/Apache Cordova

I spent some time recently trying to find out how to launch my website as a mobile app.  The information was available around the internet but since it took me a while, I thought I'd collate it here in one simple post for anyone who wants to do the same

I decided to use Apache Cordova since it gave me the framework for developing an HTML5 site as a mobile app already, meaning all I really needed to do was plug my website into it.  Their getting started guide has good information on how to create a Cordova project - I used Android but you can use whatever means you wish

A basic Cordova app gives you a way to launch the app with an HTML page that you use to display your app contents.  The trick then is make the page load your website which you can do in one of 3 ways:

1. Package your site inside the app. This means it loads fast and without an internet connection.  The downside is you have to update and re-release the app whenever your website changes. It also needs to use relative paths since the root directory will be the mobile device's root directly, not the root of your site
2. Point the page at your remote website, which means changes are picked up immediately.  The downside is that it won't work if the phone has no internet connection
3. Do both and fall back to the local site if there is no network connection

Option 1 - Package your website inside the app

If you want to do option 1 (package your site with the app) you simply copy your entire site into the assets > www directory which will load your homepage as a local page (I think PhoneGap Build insists this is index.html, but if you're loading from code you just launch Cordova with that page name). Simple. You need not read on unless you're interested in option 2 or 3

Option 2 - launch your external website inside the app

To load a remote site, you need to load your homepage (or any page) using javascript from the html page that Cordova will open in your app.  This is relatively simple using basic javascript

The recommended way to run javascript in a Cordova environment is to use Cordova's ondeviceready event which ensures it is loaded, which can be hooked into your page

document.addEventListener("deviceready", onDeviceReady, false); 
function onDeviceReady() {
    // Now safe to use the Codova API
window.location=""; }

This is probably not strictly necessary for this javascript call, which is not using the Cordova API.  However I am using because it is needed for option 3

You also need to tell Cordova that it is safe to load your website in the cordova.xml properties (you can remove the subdomains part if you don't have any)
<access origin="" subdomains="true"/>

At this point you are good to go!

Option 3 - launch your external website but fail back to local version

This option requires a little more work but gives you the advantage of displaying a set of files packaged with the app if there is no internet connection

Since you need the html page given by Cordova in assets > www you will need to copy your local site to a subdirectory (I've called it local), and do everything in option 2 to load the remote site

All you need then is to add some logic to decide whether there is an internet connection and act accordingly.  Fortunately Cordova gives us a solution to this

Firstly, add a javascript function to check the connection type

   function checkConnection() {
         var networkState =;
         var states = {};
         states[Connection.UNKNOWN]  = 'Unknown connection';
         states[Connection.ETHERNET] = 'Ethernet connection';
         states[Connection.WIFI]     = 'WiFi connection';
         states[Connection.CELL_2G]  = 'Cell 2G connection';
         states[Connection.CELL_3G]  = 'Cell 3G connection';
         states[Connection.CELL_4G]  = 'Cell 4G connection';
         states[Connection.NONE]     = 'No network connection';
         return networkState;

Then add some logic around the window.location call to load the appropriate site

   function onDeviceReady() {
   var networkState = checkConnection();
 /* load local files if there is not network connection */
                  if (networkState == Connection.NONE) {
                  } else {

Again, you're good to go!

As an alternative to option 2 or 3 (I'll call it option 2a) you could use the connection type logic to display an error message so you don't attempt to load the external site when there is no connection eg:

   function onDeviceReady() {
   var networkState = checkConnection();
 /* load local files if there is not network connection */
                  if (networkState == Connection.NONE) {
                  navigator.notification.alert('This app requires an internet connection');
                  } else {
I'm going to wrap a framework around this and release some instructions for non-developers to produce site launchers for mobile devices using PhoneGap build.  Watch this space

Tuesday, 26 February 2013

Android Daydream with Processing.js

How to create an Android Daydream with processing.js

I've spent some time working out how to get processing.js (a nice javascript graphics library ported from Processing) to display an Android Daydream (basically a screensaver that activates when the device is docked or charging)

I previously wrote about how to display an HTML page as a Daydream which forms the basis for this post.  Please see my earlier post for full details but to summarise you can load an HTML page in a webview like this

Processing.js allows you to display Processing code as javascript in a page, so all you need to do is either embed the processing.js code or load the Processing PDE file containing the code as explained on the processing.js site

I only had a couple of issues with it which were:

1. The js code seemed to run at a much higher frame rate than my native Processing code such that my animation looked insane. In the end I just reduced the frame rate to 8
 void setup() {

You might need to play with the rate for your particular animation

2. screen.width and screen.height didn't seem to work correctly and displayed my animation off the bottom of the screen.  Using window.innerWidth and window.innerHeight had the desired effect
    size(window.innerWidth, window.innerHeight);

You can test it in a local browser simply by loading the HTML page into Firefox/Chrome/whatever.  Once it's working, just follow the instructions from my earlier post to set it up as a Daydream and you're good to go :)

I've added this and released it with my Android app and will see what people think

As always, if you have any questions just let me know

Daydream running on my phone
Daydream installed