Android how to Integrate Banner and Interstitial Ads in your App(Part I)

AdMob is a multi-platform mobile ad network that allows you to monetize your android app. It is very useful particularly when you are publishing a free app and want to earn some money from it. Integrating AdMob is such an easy task that it takes not more than 5mins.

In this article, I will teach you how to integrate AdMob in your application without using Firebase. By the end of this article, you will know how to integrate 2 different types of ads in your application, Banners ads and Interstitial ads.

Type of AdMob Ads

AdMob offers a number of different ad formats, so you can choose the one that best fits your app’s user experience.

Banner Ad

Banner Ads occupies only portion of the screen depending on the ad size that is created and stays on screen while users are interacting with the app, and can refresh automatically after a certain period of time.

It comes in multiple sizes Standard, Medium, Large, Full-Size, Leaderboard, and Smart Banner.

Smart banners are very useful when you target multiple device sizes. It detects the width of the device in its current orientation and creates the ad view that size.

Interstitial Ad

Interstitial ads are full-screen ads that cover the interface of an app until closed by the user. Basically, they will shown on a timely basis, between screen transition or when the user is done with a task. Usually, we can see these ads in games displaying Ad when a level is completed.

Rewarded Video Ad

Rewarded Video Ads are fullscreen video ads which offers some reward points if the user watches the ad video. These ads are very useful to offer some reward points / coins in video games.

Native Ad

Native Ads offers flexibility to configure the ad appearance like color, text color and buttons to make them appear as native component of the app.

Setting Up AdMob

Before displaying ads and earning revenue firstly we have to do some three-step setup.

Import the Mobile Ads SDK

Add the below dependency, which instructs Gradle to pull in the latest version of the Mobile Ads SDK and additional related dependencies and then perform a Gradle sync.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

    implementation 'com.google.android.gms:play-services-ads:18.3.0'
}

Update your AndroidManifest.xml

Creating AdMob APP ID

1. Sign into your AdMob account.

2. Click on Apps option at the left side and then click on ADD APP to add an app in which you want to integrate AdMob.

Screenshot 2020-01-24 12.11.21

3. Now it will ask one question that the app in which you want to add AdMob is already published on Google Play or the App Store. In our case say No.

Screenshot 2020-01-24 12.12.26

4. Provide the application name, select the platform in which you have created your app and then finally click on ADD.

Screenshot 2020-01-24 12.13.32

5. Once the App is added to AdMob, you can find the APP ID on the dashboard which looks like ca-app-pub-XXXXXXXXX~XXXXXXXXX.

Adding AdMob App Id in ManifestFile

Add your AdMob App ID to your app’s AndroidManifest.xml file by adding a  tag with name com.google.android.gms.ads.APPLICATION_ID, as shown below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidadmobdemo">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ENTER YOUR ADMOB APP ID" />

</application>

</manifest>

Initialize Mobile Ads SDK

Create a class named MyApplication.java and extend the class from Application. In this application class we have to globally initialize the AdMob App Id. Here we use MobileAds.initialize() method to initialize the AdMob.

MyApplication.java

package com.example.androidadmobdemo;

import android.app.Application;

import com.google.android.gms.ads.MobileAds;

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        //initializes Mobile Ads SDK
        MobileAds.initialize(this, "ENTER YOUR ADMOB APP_ID");
    }
}

Open AndroidManifest.xml and add MyApplication to <application> tag to execute the class on app launch.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidadmobdemo">

<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<activity
android:name=".InterstitialAdActivity"
android:label="Interstitial" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-9620678622149713~7105710424" />
</application>

</manifest>

Creating Ad Units

1. Sign into your AdMob account.

2 . From the left side click on Apps and then select the newly created App(In my case AndroidAdMobDemo).

3. Inside your App name select Ad units and click on ADD AD UNIT button to create a new ad unit.

Screenshot 2020-01-24 13.17.28

4. Select the ad format and give the ad unit a name.

5. Once the ad unit is created, you can notice the Ad unit ID on the dashboard. An example of ad unit id looks like ca-app-pub-962XXXXXXX/XXXXXXXXXXX.

Create as many ad units as required for your app.

Adding Banner Ad

Banner ads occupy only a portion of the screen. I am adding a banner ad in my main activity aligning to bottom of the screen. In order to add the banner ad, you need to add com.google.android.gms.ads.AdView element to your xml layout.

<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-3940256099942544/6300978111"/>

There are two different parameters that you should notice here, adUnitId  and adSize . adUnitId is the unique ID that identifies your single ad unit. Here the ID that we have used is a test ID provided by Google. Always use test ID when you are developing/testing an app. A real ID should only be used in production.

ca-app-pub-3940256099942544/6300978111

adSize defines the size of your banner, there are various banner sizes available which must have a look at here.

You can also add an AdView dynamically :

AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");

//add adview to your view hierarchy
viewGroup.addChild(adView);

Open the layout file of your main activity (activity_main.xml) and add the AdView widget. I am also adding a button to launch another activity in which we’ll try Interstitial ad.

activity_main.xml

package com.example.androidadmobdemo;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private AdView mAdView;
Button btnFullScreenAd;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mAdView = findViewById(R.id.adView);

btnFullScreenAd = findViewById(R.id.btn_fullscreen_ad);
btnFullScreenAd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, InterstitialAdActivity.class));
}
});

AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();

mAdView.loadAd(adRequest);

mAdView.setAdListener(new AdListener() {

// Code to be executed when an ad finishes loading.
@Override
public void onAdLoaded() {
}

//Code to be executed when an ad opens an overlay that
// covers the screen.
@Override
public void onAdOpened() {
super.onAdOpened();
}

// Code to be executed when an ad request fails.
@Override
public void onAdFailedToLoad(int errorCode) {
Toast.makeText(getApplicationContext(), "Ad failed to load! error code: " + errorCode, Toast.LENGTH_SHORT).show();
}

//called after onAdOpened(), when a user click opens another app (such as the Google Play), backgrounding the current app
@Override
public void onAdLeftApplication() {
Toast.makeText(getApplicationContext(), "Ad left application!", Toast.LENGTH_SHORT).show();
}

// Code to be executed when the user clicks on an ad.
@Override
public void onAdClicked() {

}

// Code to be executed when the user is about to return
// to the app after tapping on an ad.
@Override
public void onAdClosed() {
Toast.makeText(getApplicationContext(), "Ad is closed!", Toast.LENGTH_SHORT).show();
}
});

}
@Override
public void onPause() {
if (mAdView != null) {
mAdView.pause();
}
super.onPause();
}

@Override
public void onResume() {
super.onResume();
if (mAdView != null) {
mAdView.resume();
}
}

@Override
public void onDestroy() {
if (mAdView != null) {
mAdView.destroy();
}
super.onDestroy();
}
}

Loading Ad

After adding the AdView, we will now load an ad into it.

public class MainActivity extends AppCompatActivity {

private AdView mAdView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mAdView = findViewById(R.id.adView);

AdRequest adRequest = new AdRequest.Builder()
.build();

mAdView.loadAd(adRequest);
}

Get a reference to the AdView, create a AdRequest object, load the ad by calling loadAd on the AdView reference and passing adRequest into it.

Handling ad events

To further customize the behavior of your ad, you can hook onto a number of events in the ad’s lifecycle: loading, opening, closing, and so on. You can listen for these events through the AdListener class.

To use an AdListener with AdView, simply call the setAdListener() method:

mAdView.setAdListener(new AdListener() {

// Code to be executed when an ad finishes loading.
@Override
public void onAdLoaded() {
}

//Code to be executed when an ad opens an overlay that
// covers the screen.
@Override
public void onAdOpened() {
super.onAdOpened();
}

// Code to be executed when an ad request fails.
@Override
public void onAdFailedToLoad(int errorCode) {
Toast.makeText(getApplicationContext(), "Ad failed to load! error code: " + errorCode, Toast.LENGTH_SHORT).show();
}

//called after onAdOpened(), when a user click opens another app 
//(such as the Google Play), backgrounding the current app
@Override
public void onAdLeftApplication() {
Toast.makeText(getApplicationContext(), "Ad left application!", Toast.LENGTH_SHORT).show();
}

// Code to be executed when the user clicks on an ad.
@Override
public void onAdClicked() {

}

// Code to be executed when the user is about to return
// to the app after tapping on an ad.
@Override
public void onAdClosed() {
Toast.makeText(getApplicationContext(), "Ad is closed!", Toast.LENGTH_SHORT).show();
}
});

Open MainActivity.java and modify the code as shown.

  • Create an instance of AdRequest and load the ad into AdView.
  • Add the AdView life cycle methods in onResume(), onPause() and in onDestroy() methods.

MainActivity.Java

package com.example.androidadmobdemo;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {

private AdView mAdView;
Button btnFullScreenAd;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mAdView = findViewById(R.id.adView);

btnFullScreenAd = findViewById(R.id.btn_fullscreen_ad);
btnFullScreenAd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, InterstitialAdActivity.class));
}
});

AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();

mAdView.loadAd(adRequest);

mAdView.setAdListener(new AdListener() {

// Code to be executed when an ad finishes loading.
@Override
public void onAdLoaded() {
}

//Code to be executed when an ad opens an overlay that
// covers the screen.
@Override
public void onAdOpened() {
super.onAdOpened();
}

// Code to be executed when an ad request fails.
@Override
public void onAdFailedToLoad(int errorCode) {
Toast.makeText(getApplicationContext(), "Ad failed to load! error code: " + errorCode, Toast.LENGTH_SHORT).show();
}

//called after onAdOpened(), when a user click opens another app (such as the Google Play), backgrounding the current app
@Override
public void onAdLeftApplication() {
Toast.makeText(getApplicationContext(), "Ad left application!", Toast.LENGTH_SHORT).show();
}

// Code to be executed when the user clicks on an ad.
@Override
public void onAdClicked() {

}

// Code to be executed when the user is about to return
// to the app after tapping on an ad.
@Override
public void onAdClosed() {
Toast.makeText(getApplicationContext(), "Ad is closed!", Toast.LENGTH_SHORT).show();
}
});
}

@Override
public void onPause() {
if (mAdView != null) {
mAdView.pause();
}
super.onPause();
}

@Override
public void onResume() {
super.onResume();
if (mAdView != null) {
mAdView.resume();
}
}

@Override
public void onDestroy() {
if (mAdView != null) {
mAdView.destroy();
}
super.onDestroy();
}
}

Note: Always use test Ad ID while you are testing your application, you should never use original Ad ID in your application when in testing/developing phase. If you do so you might get blocked from AdMob.

Now if you run the app, you should see a banner ad at the bottom of your screen.

Screenshot_1580134151

Adding Interstitial Ad

Interstitial ads occupies full screen of the app. Normally these ads will be populated when user is moving between activities or moving to next level when playing a game.

When creating interstitial ads, we don’t need to define any view in your layout file, these can only be created programmatically.

Make a global variable of InterstitialAd, initialize the variable in onCreate and set the AdUnitId.

public class InterstitialAdActivity extends AppCompatActivity {

InterstitialAd mInterstitialAd;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_interstitial_ad);

mInterstitialAd = new InterstitialAd(this);

// setting ad unit ID
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
   }

 }

Google provides a testing id for interstitial ad, make sure to use exactly this ID when testing/debugging your application.

ca-app-pub-3940256099942544/1033173712

Now we need to load the ad.

AdRequest adRequest = new AdRequest.Builder()
.build();

mInterstitialAd.loadAd(adRequest);

Let’s show the ad. Always check if the ad is loaded before showing it.

private void showInterstitial() {

// Show the ad if it's ready. Otherwise toast and restart the game.
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show();
//play game
}
}

We’ll test this ad by creating a second activity and popup the full-screen ad when the second activity is launched.

Create an activity named InterstitialAdActivity.java by right-clicking on package New Activity Empty Activity.

InterstitialAdActivity.java

package com.example.androidadmobdemo;

import android.os.Bundle;
import android.widget.Toast;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;

import androidx.appcompat.app.AppCompatActivity;

public class InterstitialAdActivity extends AppCompatActivity {

InterstitialAd mInterstitialAd;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_interstitial_ad);


mInterstitialAd = new InterstitialAd(this);

// setting ad unit ID
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");

AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();

mInterstitialAd.loadAd(adRequest);

mInterstitialAd.setAdListener(new AdListener() {

// Code to be executed when an ad finishes loading.
public void onAdLoaded() {
showInterstitial();
}

// Code to be executed when the user is about to return
// to the app after tapping on an ad.
@Override
public void onAdClosed() {
Toast.makeText(getApplicationContext(), "Ad is closed!", Toast.LENGTH_SHORT).show();
}

// Code to be executed when an ad request fails.
@Override
public void onAdFailedToLoad(int errorCode) {
Toast.makeText(getApplicationContext(), "Ad failed to load! error code: " + errorCode, Toast.LENGTH_SHORT).show();
}

//called after onAdOpened(), when a user click opens another app (such as the Google Play), backgrounding the current app
@Override
public void onAdLeftApplication() {
Toast.makeText(getApplicationContext(), "Ad left application!", Toast.LENGTH_SHORT).show();
}

//Code to be executed when an ad opens an overlay that
// covers the screen.
@Override
public void onAdOpened() {
Toast.makeText(getApplicationContext(), "Ad is opened!", Toast.LENGTH_SHORT).show();
}
});
}

private void showInterstitial() {

// Show the ad if it's ready. Otherwise toast and restart the game.
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show();
//play game
}
}

}

Now if you run the app, you can see the interstitial ad when the second activity is launched.

Screenshot_1580134026

In the next article(ie. Part II) we will talk about how to integrate other two ads in our application ie. Rewarded video ads and Native Ads in brief.

Leave a Reply