Monetize With Google Admob In An Ionic 2 Mobile App

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):

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:

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:

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

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:

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.

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:

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 is a skilled application developer who has released several native and hybrid mobile applications to iTunes and Google Play. He writes about his development experiences related to making web and mobile app development easier to understand and has experience in Android, Node.js, Apache Cordova, Java, NoSQL, SQL, GoLang, NativeScript, and Unity3D.

  • How can I use adModPro with ionic 1, do you have some reference tutorial?

  • ashraful haque

    here Interstitial add showing only once

    • There are three interstitial functions:

      When you call showInterstitial it should show the last prepared ad. Preparing an interstitial should create a new ad. If the ad is not showing you may want to make use of isInterstitialReady. If none of this works, please share your logs, even if there are no errors.

      Regards,

  • ashraful haque

    Now working.

  • ashraful haque

    TypeScript error: G:/cordova/need4test2/app/pages/home/home.ts(15,13): Error TS2663: Cannot find name ‘admobId’. Did you mean the instance member ‘this.admobId’?
    TypeScript error: G:/cordova/need4test2/app/pages/home/home.ts(20,13): Error TS2663: Cannot find name ‘admobId’. Did you mean the instance member ‘this.admobId’?
    TypeScript error: G:/cordova/need4test2/app/pages/home/home.ts(29,16): Error TS2304: Cannot find name ‘AdMob’.
    TypeScript error: G:/cordova/need4test2/app/pages/home/home.ts(30,17): Error TS2304: Cannot find name ‘AdMob’.

    Not working with new beta update, but works well with older beta. plz update, Thanks in advance

  • ashraful haque

    Ionic beta ten my apps.ts code is below

    import {Component} from ‘@angular/core’;
    import {Platform, ionicBootstrap} from ‘ionic-angular’;
    import {StatusBar} from ‘ionic-native’;
    import {TabsPage} from ‘./pages/tabs/tabs’;

    @Component({
    template: ”
    })
    export class MyApp {

    private rootPage:any;

    constructor(private platform:Platform) {
    this.rootPage = TabsPage;

    // select the right Ad Id according to platform
    if( /(android)/i.test(navigator.userAgent) ) {
    admobid = { // for Android
    banner: ‘ca-app-pub-6869992474017983/9375997553’,
    interstitial: ‘ca-app-pub-6869992474017983/1657046752’
    };
    } else if(/(ipod|iphone|ipad)/i.test(navigator.userAgent)) {
    admobid = { // for iOS
    banner: ‘ca-app-pub-6869992474017983/4806197152’,
    interstitial: ‘ca-app-pub-6869992474017983/7563979554’
    };
    } else {
    admobid = { // for Windows Phone
    banner: ‘ca-app-pub-6869992474017983/8878394753’,
    interstitial: ‘ca-app-pub-6869992474017983/1355127956’
    };
    }
    if(AdMob) AdMob.createBanner( admobid.banner );
    // preppare and load ad resource in background, e.g. at begining of game level
    if(AdMob) AdMob.prepareInterstitial( {adId:admobid.interstitial, autoShow:false} );

    // show the interstitial later, e.g. at end of game level
    if(AdMob) AdMob.showInterstitial();

    }
    }

    ionicBootstrap(MyApp)

    and for that error is as below

    ionic $ TypeScript error: app/app.ts(40,4): Error TS2304: Cannot find name ‘AdMob’.
    TypeScript error: app/app.ts(40,11): Error TS2304: Cannot find name ‘AdMob’.
    TypeScript error: app/app.ts(40,39): Error TS2339: Property ‘banner’ does not exist on type ‘{}’.
    TypeScript error: app/app.ts(42,4): Error TS2304: Cannot find name ‘AdMob’.
    TypeScript error: app/app.ts(42,11): Error TS2304: Cannot find name ‘AdMob’.
    TypeScript error: app/app.ts(42,52): Error TS2339: Property ‘interstitial’ does not exist on type ‘{}’.

    What is the problem. It was working in previous verson, but in new ionic beta 10, showing error

    • I just updated the tutorial to use TypeScript. It was using JavaScript previously. If you’re reading my tutorials I recommend paying attention to whether or not I use TS files or JS files. TypeScript project’s more than likely will not work with JavaScript code.

      Tested it and it works fine.

      Best,

  • Mukul Sharma

    i want to create app within my ionic application without creating in monetize dashboards. Can i do that ?

  • Mukul Sharma

    I want to create AdMob Ads within my ionic application without creating in monetize dashboards. Can i do that ?

  • iosp0iss0n

    i add admob to my app and it is working the only issue i have is that the link i provide on my app (use suppose to open with Sopcast ) don’t work any more when ads are showing
    This is my app.js

    // Ionic Starter App

    // angular.module is a global place for creating, registering and retrieving Angular modules
    // ‘starter’ is the name of this angular module example (also set in a attribute in index.html)
    // the 2nd parameter is an array of ‘requires’
    // ‘starter.services’ is found in services.js
    // ‘starter.controllers’ is found in controllers.js
    angular.module(‘app’, [‘ionic’, ‘app.controllers’, ‘app.routes’, ‘app.directives’,’app.services’,’firebase’,’firebaseConfig’,])

    .config(function($ionicConfigProvider, $sceDelegateProvider){

    $sceDelegateProvider.resourceUrlWhitelist([ ‘self’,’://www.youtube.com/‘, ‘://player.vimeo.com/video/‘]);

    })

    .run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    cordova.plugins.Keyboard.disableScroll(true);
    }
    if (window.StatusBar) {
    // org.apache.cordova.statusbar required
    StatusBar.styleDefault();
    }

    if(window.AdMob) AdMob.createBanner( {
    adId:admobid.banner,
    position:AdMob.AD_POSITION.BOTTOM_CENTER,
    autoShow:true} );
    });
    })

    .directive(‘disableSideMenuDrag’, [‘$ionicSideMenuDelegate’, ‘$rootScope’, function($ionicSideMenuDelegate, $rootScope) {
    return {
    restrict: “A”,
    controller: [‘$scope’, ‘$element’, ‘$attrs’, function ($scope, $element, $attrs) {

    }])

    and this is my html template

    the only one not working on my app are the one beginin with “sop://” and this is only when ads are on ,with no ads everything works just fine,any idea ???many thanks

  • Davide D. Troise

    Isn’t out there a way to add Ads in an Ionic2 app without having an AdSense account? I was banned ages ago!
    Thank you!

    • Google AdMob is the most popular. There are other ad services, but you’re probably going to have a tough time finding Apache Cordova plugins.

      • Davide D. Troise

        Yes i’m already having troubles =P
        Thank you anyway

  • Pheng Sengvuthy

    Hello everyone, I have followed your code above and it works as well, but about banner ads, sometime it works sometime it does not work.
    I now need your advices please!

    • If Google feels there are no appropriate ads to display in your application, it won’t display any. This applies to websites as well. Ads are displayed based on relevancy and if you have a niche application where it doesn’t make sense to display ads, none will show.

      If you feel this is not right, you may want to contact Google.

      Best,

  • Sasha Carvajal Larios

    Hi! Great post!! Do you know how does ad rewards work?? I want yo implement them but cant any tutorials 🙁

    Thanks!

  • Felipe Maroni

    Hi Nic, good tutorial!
    But, admob banner needs margin according to google policy or can i use it together device buttoms?

  • Pheng Sengvuthy

    If I want to set event on Intertitial when it is dismissed. How could I ?

  • Stevie Starosciak

    Hey there Nic, your tutorials are as awesome as ever. The one thing I’m running into is even though I’ve replaced the adId for both banner and interstitial, both of which I have created inside of my AdMob app, when I click the button for createBanner and show/hide banner, all it does is show a white rectangle at the bottom of my app without any kind of ad inside of it.

    Have I done something to misconfigure something on either the app or within my AdMob account?

    • Are you in test mode? Did you just recently setup Admob? Are you in a country which doesn’t support ads?

      Those are all possible reasons why they won’t show. People tell me he country thing is a big one, but I say give it a day or two and see if ads start appearing.