Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Monetize With Google Admob In An Ionic Mobile App

TwitterFacebookRedditLinkedInHacker News

So you made a shiny new app and want to earn some money from it. The paid revenue model may not be the best fit for you, so instead you might want to consider ads. The more popular Google Admob solution makes advertising incredibly simple and best of all it can be used within an Ionic 2 Android and iOS application.

If you’ve been keeping up with my blog, you’ll know that I wrote about using Admob in an Ionic Framework 1 mobile app a while back. Things have changed since then, both in the framework and the particular plugin used.

To display Google Admob ads within your application you will need an Admob account with good standing. It should be noted that not all countries allow the use of Admob and often ads will take a few days to show after being registered. With that said we can move along.

Let’s start by creating a fresh Ionic 2 project from the Command Prompt (Windows) or Terminal (Mac and Linux):

ionic start ExampleProject blank --v2 --typescript
cd ExampleProject
ionic platform add ios
ionic platform add android

A few things to note here. You cannot add and build for the iOS platform unless you’re using a Mac. You also need to be using the Ionic CLI that supports version two of the framework.

To get ads in our Android and iOS application we’re going to make use of the cordova-admob-pro plugin by Raymond Xie. This plugin can be installed by executing the following:

ionic plugin add cordova-plugin-admobpro

Going forward I’m going to state that bits of pieces of our code was taken directly from the official plugin documentation. Much of what comes next was customized by myself.

The core of our work will be in the app/pages/home/home.ts and app/pages/home/home.html files. Of course one file will contain our UI and the other our logic. Let’s start with the logic file.

Open your app/pages/home/home.ts file and include the following code:

import {Component} from '@angular/core';
import {NavController, Platform} from 'ionic-angular';

declare var AdMob: any;

@Component({
    templateUrl: 'build/pages/home/home.html'
})
export class HomePage {

    private admobId: any;

    constructor(private navController: NavController, private platform: Platform) {
        this.platform = platform;
        if(/(android)/i.test(navigator.userAgent)) {
            this.admobId = {
                banner: 'ca-app-pub-xxx/yyy',
                interstitial: 'ca-app-pub-jjj/kkk'
            };
        } else if(/(ipod|iphone|ipad)/i.test(navigator.userAgent)) {
            this.admobId = {
                banner: 'ca-app-pub-ddd/sss',
                interstitial: 'ca-app-pub-ppp/zzz'
            };
        }
    }

    createBanner() {
        this.platform.ready().then(() => {
            if(AdMob) {
                AdMob.createBanner({
                    adId: this.admobId.banner,
                    autoShow: false
                });
            }
        });
    }

    showInterstitial() {
        this.platform.ready().then(() => {
            if(AdMob) {
                AdMob.prepareInterstitial({
                    adId: this.admobId.interstitial,
                    autoShow: true
                });
            }
        });
    }

    showBanner(position) {
        this.platform.ready().then(() => {
            if(AdMob) {
                var positionMap = {
                    "bottom": AdMob.AD_POSITION.BOTTOM_CENTER,
                    "top": AdMob.AD_POSITION.TOP_CENTER
                };
                AdMob.showBanner(positionMap[position.toLowerCase()]);
            }
        });
    }

    hideBanner(position) {
        this.platform.ready().then(() => {
            if(AdMob) {
                AdMob.hideBanner();
            }
        });
    }

}

Let’s break down what this big chunk of code is doing starting with the constructor method.

if (/(android)/i.test(navigator.userAgent)) {
    admobId = {
        banner: 'ca-app-pub-xxx/yyy',
        interstitial: 'ca-app-pub-jjj/kkk'
    };
} else if(/(ipod|iphone|ipad)/i.test(navigator.userAgent)) {
    admobId = {
        banner: 'ca-app-pub-ddd/sss',
        interstitial: 'ca-app-pub-ppp/zzz'
    };
}

This was pulled from the documentation. We are essentially just defining our Admob publisher values. Although we could just use a single publisher value for everything, it wouldn’t be smart from an analytics perspective. We want to be able to track Android and iOS separately.

Now we have a bunch of functions that will do different things with the advertisements. Before showing a banner advertisement we must first create it like so:

createBanner() {
    this.platform.ready().then(() => {
        if(AdMob) {
            AdMob.createBanner({
                adId: admobId.banner,
                autoShow: false
            });
        }
    });
}

We need to make sure the plugin is ready before use which is why we wrap it in a platform.ready. We also have to make sure Admob exists. If we’re in the browser it won’t exist, likewise if the plugin didn’t install correctly.

showBanner(position) {
    this.platform.ready().then(() => {
        if(AdMob) {
            var positionMap = {
                "bottom": AdMob.AD_POSITION.BOTTOM_CENTER,
                "top": AdMob.AD_POSITION.TOP_CENTER
            };
            AdMob.showBanner(positionMap[position.toLowerCase()]);
        }
    });
}

With the banner advertisement created we can show it. In this function we pass in a position variable to represent a top or bottom placement. We created a map to reflect the values.

I’m pretty sure you can figure out the other two functions used in the full logic file since they aren’t any different.

Now we can jump into the UI. Open the project’s app/pages/home/home.html and include the following code:

<ion-header>
    <ion-navbar>
        <ion-title>Ionic Blank</ion-title>
    </ion-navbar>
</ion-header>

<ion-content class="home" padding>
    <button default (click)="createBanner()">Create Banner</button>
    <button secondary (click)="showBanner('bottom')">Show Banner</button>
    <button dark (click)="hideBanner()">Hide Banner</button>
    <button light (click)="showInterstitial()">Show Interstitial</button>
</ion-content>

In our UI we only have four buttons that trigger the functions we made previously. This allows us to create ads and show them.

Try playing around with the create button. Notice that every time you call createBanner it generates a new ad. Be careful with this. Your revenue will decrease if your impressions outweigh your clicks. Every time you regenerate an ad it counts as a new impression.

Conclusion

Just like we saw with my previous tutorial for using Admob with Ionic Framework 1, using it with Ionic 2 isn’t too different or difficult. Advertisements are a great way to monetize an application. It can be used instead of a paid approach or in combination making a freemium model.

From a personal note, my applications did not start earning more than a few dollars from Google Admob advertisements until I had more than ten thousand users.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.