Implement AdMob Native Plugin In Ionic 5 Applications More Efficiently

0
780

As the latest stable version of Ionic 5 is released. in this article we i am going to explain Implement AdMob Native Plugin In Ionic 5. As we all know that we can add three types of AdMob ads in a hybrid application like Ionic for now, which are Banner AdsInterstitial Ads ad Reward Video Ads.

Create A New Ionic 5 Application

Don’t forget to update your Ionic CLI to latest version using below command

 npm install -g ionic
Creating a new ionic application

Let us start a new ionic application using the following command

ionic start Ionic4AdMobFree blank
cd Ionic4AdMobFree

Add AdMob Native Plugin In Ionic 5 Applications

Install the AdMob Native Plugin In Ionic 5 using the following npm commands.

AdMob Native Plugin In Ionic 5

You can read more about how to get App ID from AdMob site here

ionic cordova plugin add cordova-plugin-admob-free  --save --variable ADMOB_APP_ID="YOUR_ADMOB_ADMOB_APP_ID"
npm install @ionic-native/admob-free

Related Post: Creating Tab Layout in Ionic

Service For AdMob Methods

Next, we will create a new AdMob service under a service folder to keep three of our methods to show all three type of Ads in the application.

Create a new service using the following command

ionic g service ./services/admob

Once the service is created successfully, we must configure the AdMob methods in that. Your service file must like the following

import { Injectable } from '@angular/core';
import {
  AdMobFree,
  AdMobFreeBannerConfig,
  AdMobFreeInterstitialConfig,
  AdMobFreeRewardVideoConfig
} from '@ionic-native/admob-free/ngx';
import {Platform} from '@ionic/angular';

@Injectable({
  providedIn: 'root'
})
export class AdmobService {
  // Interstitial Ad's Configurations
  interstitialConfig: AdMobFreeInterstitialConfig = {
    isTesting: true,
    autoShow: false,
    // id: 'ca-app-pub-2690342244122071/2681551506'
  };

  // Reward Video Ad's Configurations
  RewardVideoConfig: AdMobFreeRewardVideoConfig = {
    isTesting: true,
    autoShow: false,
    // id: 'ca-app-pub-2690342244122071/1368469837'
  };
  constructor(private admobFree: AdMobFree,
              public platform: Platform) {
    platform.ready().then(() => {

      // Load ad configuration
      this.admobFree.interstitial.config(this.interstitialConfig);
      // Prepare Ad to Show
      this.admobFree.interstitial.prepare()
          .then(() => {
            // alert(1);
          }).catch(e => alert(e));


      // Load ad configuration
      this.admobFree.rewardVideo.config(this.RewardVideoConfig);
      // Prepare Ad to Show
      this.admobFree.rewardVideo.prepare()
          .then(() => {
            // alert(2);
          }).catch(e => alert(e));

    });

    // Handle interstitial's close event to Prepare Ad again
    this.admobFree.on('admob.interstitial.events.CLOSE').subscribe(() => {
      this.admobFree.interstitial.prepare()
          .then(() => {
            alert('Interstitial CLOSE');
          }).catch(e => alert(e));
    });
    // Handle Reward's close event to Prepare Ad again
    this.admobFree.on('admob.rewardvideo.events.CLOSE').subscribe(() => {
      this.admobFree.rewardVideo.prepare()
          .then(() => {
            alert('Reward Video CLOSE');
          }).catch(e => alert(e));
    });
  }

  BannerAd() {
    const bannerConfig: AdMobFreeBannerConfig = {
      isTesting: true, // Remove in production
      autoShow: true,
      // id: 'ca-app-pub-2690342244122071/9970685177'
    };
    this.admobFree.banner.config(bannerConfig);

    this.admobFree.banner.prepare().then(() => {
      // success
    }).catch(e => alert(e));
  }

  InterstitialAd() {
    // Check if Ad is loaded
    this.admobFree.interstitial.isReady().then(() => {
      // Will show prepared Ad
      this.admobFree.interstitial.show().then(() => {
      })
          .catch(e => alert('show ' + e));
    })
        .catch(e => alert('isReady ' + e));
  }

  RewardVideoAd() {
    // Check if Ad is loaded
    this.admobFree.rewardVideo.isReady().then(() => {
      // Will show prepared Ad
      this.admobFree.rewardVideo.show().then(() => {
      })
          .catch(e => alert('show ' + e));
    })
        .catch(e => alert('isReady ' + e));
  }
}

For Interstitial and Reward Video Ads we have added configuration part before constructor, in platform ready event we are preparing both these ad type with content. After when these both ads are shown up and closed, then on CLOSE event these will prepare again.

You can check more events here

This method will prevent ads to show up after the user exit the application which is a violation of Google Play store policies.

Import Your Plugin in AppModule

You must import the AdMod free plugin under the provider section. Your AppModule file should be like the following

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import {AdMobFree} from '@ionic-native/admob-free/ngx';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule
  ],
  providers: [
    StatusBar,
    AdMobFree,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Preparing Template Section

Next, we will update Home page HTML file to call these Ads.

<ion-content [fullscreen]="true">
  <ion-header collapse="condense">
    <ion-toolbar>
      <ion-title size="large">Home</ion-title>
    </ion-toolbar>
  </ion-header>

  <ion-grid>
    <ion-row>
      <ion-col>
        <ion-button (click)="showInterstitial()">Show Interstitial Ad</ion-button>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col>
        <ion-button (click)="showRewardVideo()">Show Reward Video Ad</ion-button>
      </ion-col>
    </ion-row>
  </ion-grid>

Preparing the Component Class

Next, we will update Home page component class file to call these Ads.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import {AdmobService} from '../services/admob.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit {
  public folder: string;

  constructor(private activatedRoute: ActivatedRoute, private admobFreeService: AdmobService) { }

  ngOnInit() {
    this.folder = this.activatedRoute.snapshot.paramMap.get('id');
    this.admobFreeService.BannerAd();
  }

  showInterstitial() {
    this.admobFreeService.InterstitialAd();
  }

  showRewardVideo() {
    this.admobFreeService.RewardVideoAd();
  }

}

Test the Application in Device

After updating your app with the above code, you can run and check on a real device by running following command

ionic cordova run android --device

Related Post: Ionic 5 New Features