How to add Admob ad (Banner/Interstitial/Rewarded) in Android

Share Post
  •  
  •  
  • 1
  • 2
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    3
    Shares

Please Subscribe Youtube| Like Facebook | Follow Twitter

For Kotlin follow this article

Introduction

In this article we will learn how to implement Admob Banner/Interstitial/Rewarded Ads in android application. Admob allows you to monetize your app by displaying ads.

Our Example

In our example we have two button which will display Interstitial and Reward video Ads respectively on button click. At the bottom of app screen we will display banner ad.

Requirements:

  1. Android Project/App in which admob ads to be implemented
  2. Admob Account

Steps

Follow below steps

1) Create or Sign-in Admob Account and add application

2) Create Ad units in Admob account

3) Integrate and code Admob ads in your app

4) Run and test your application

1) Create or Sign-in Admob Account and add application

Sign into or sign up for an AdMob account.

After creating account select Apps->ADD APP

If your app is not published select no and add new app.

If your app is published click yes and provide app url and link app.

Now after adding app next step is to create ad unit id.

2) Create Ad units in Admob account

Select Apps -> Ad units -> ADD AD UNIT

Select Banner Add and write any unit name and then click on create ad unit.

After creating ad unit copy app id and banner ad unit id in a text file (we will need this later).

Similarly create Interstitial and Rewarded Ads unit ad id’s and copy them to text file. For demo purpose enter any reward amount in reward video ad, in production enter amount according to your requirements.

3) Integrate and code Admob ads in your app

First add play-services-ads library at app level build.gradle file and sync project

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

In manifest file inside application tag add meta-data tag and add your own app id which was saved earlier in text file in step 2. For demo purpose we have added sample app id “ca-app-pub-3940256099942544~3347511713”.

    <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">
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-3940256099942544~3347511713"/>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

Below is the layout file code. Inside adview tag under ads:adUnitId enter your banner ad unit id which was copied in text file during step 2.

Here we have used sample test ad unit id “ca-app-pub-3940256099942544/6300978111” for testing.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >

    <Button
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Display InterstitialAd"
        android:onClick="displayInterstitialAd"
    />
    <Button
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Display Reward Video Ad"
        android:onClick="displayRewardVideoAd"
        />
    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="5"
        />
    <com.google.android.gms.ads.AdView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:id="@+id/adView"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111"
        ads:adSize="BANNER"
        xmlns:ads="http://schemas.android.com/apk/res-auto">
    </com.google.android.gms.ads.AdView>

</LinearLayout>

On app start we have initialized admob sdk in initAdmobSdk() method

private void initAdmobSdk() {
        RequestConfiguration configuration =
                new RequestConfiguration.Builder().build();
        MobileAds.setRequestConfiguration(configuration);
        MobileAds.initialize(getApplicationContext(), new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });
    }

After sdk initialization we have requested and loaded banner ad inside adView Object from xml layout. We have also defined ad listener which will be called on different event of ad life cycle, you can define any other required behaviour here.   

private void initBannerAdmob() {
        adView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);
        //define any required action in listener methods
        adView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                // Code to be executed when an ad finishes loading.
            }
            @Override
            public void onAdFailedToLoad(int errorCode) {
                // Code to be executed when an ad request fails.
            }
            @Override
            public void onAdOpened() {
                // Code to be executed when an ad opens an overlay that
                // covers the screen.
            }
            @Override
            public void onAdClicked() {
                // Code to be executed when the user clicks on an ad.
            }
            @Override
            public void onAdLeftApplication() {
                // Code to be executed when the user has left the app.
            }
            @Override
            public void onAdClosed() {
                // Code to be executed when the user is about to return
                // to the app after tapping on an ad.
            }
        });
    }

In initInterstitialAd() method we have created InterstitialAd object, which will request and load Interstitial ad. Inside setAdUnitId() enter your Interstitial Ad unit id which was copied in step 2. Here we have used sample test id “ca-app-pub-3940256099942544/1033173712” for testing. Listener is also define to define your custom action on particular ad event. onAdClosed() we have loaded next  Interstitial Ad.

private void initInterstitialAd() {
        interstitialAd = new InterstitialAd(getApplicationContext());
        interstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
        interstitialAd.loadAd(new AdRequest.Builder().build());
        interstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                // Code to be executed when an ad finishes loading.
            }
            @Override
            public void onAdFailedToLoad(int errorCode) {
                // Code to be executed when an ad request fails.
            }
            @Override
            public void onAdOpened() {
                // Code to be executed when the ad is displayed.
            }
            @Override
            public void onAdClicked() {
                // Code to be executed when the user clicks on an ad.
            }
            @Override
            public void onAdLeftApplication() {
                // Code to be executed when the user has left the app.
            }
            @Override
            public void onAdClosed() {
                // Code to be executed when the interstitial ad is closed.
                // Load the next interstitial or you can load acc to your requirements
                interstitialAd.loadAd(new AdRequest.Builder().build());
            }
        });
    }

displayInterstitialAd() will display Interstitial ad on button click. If ad is not loaded then it will display toast message.

public void displayInterstitialAd(View view) {
        if (interstitialAd.isLoaded()) {
            interstitialAd.show();
        } else {
            Toast.makeText(getApplicationContext(),"Interstitial Ad Is Not Loaded Yet",Toast.LENGTH_SHORT).show();
        }
    }

initRewardedAd() method will request and load reward video ad. Inside rewardedAd constructor’s 2nd argument enter your reward ad unit id which was copied during step 2. Here we have used sample reward test unit Id “ca-app-pub-3940256099942544/5224354917”. RewardedAdLoadCallback is also defined to check ad Load status.

public RewardedAd loadRewardedAd() {
	RewardedAd rewardedAd = new RewardedAd(getApplicationContext(),
			"ca-app-pub-3940256099942544/5224354917");
	RewardedAdLoadCallback adLoadCallback = new RewardedAdLoadCallback() {
		@Override
		public void onRewardedAdLoaded() {
			// Ad successfully loaded.
		}

		@Override
		public void onRewardedAdFailedToLoad(int errorCode) {
			// Ad failed to load.
		}
	};
	rewardedAd.loadAd(new AdRequest.Builder().build(), adLoadCallback);
	return rewardedAd;
}

public void displayInterstitialAd(View view) {
	if (interstitialAd.isLoaded()) {
		interstitialAd.show();
	} else {
		Toast.makeText(getApplicationContext(),"Interstitial Ad Is Not Loaded Yet",Toast.LENGTH_SHORT).show();
	}
}

displayRewardVideoAd() method will show reward ad on button click. Listener is also define to define your custom action on particular ad event. onRewardedAdClosed () we have loaded next  rewarded video Ad. onUserEarnedReward() method will be called when user earns the reward after successfully watching reward video ad.

public void displayRewardVideoAd(View view) {
        if (rewardedAd.isLoaded()) {
            RewardedAdCallback adCallback = new RewardedAdCallback() {
                @Override
                public void onRewardedAdOpened() {
                    // Ad opened.
                }

                @Override
                public void onRewardedAdClosed() {
                    // Ad closed.
                    // Load the next reward ad or you can load acc to your requirements
                    rewardedAd = loadRewardedAd();
                }

                @Override
                public void onUserEarnedReward(@NonNull RewardItem reward) {
                    // User earned reward.
                }

                @Override
                public void onRewardedAdFailedToShow(int errorCode) {
                    // Ad failed to display.
                }
            };
            rewardedAd.show(this, adCallback);
        } else {
            Toast.makeText(getApplicationContext(),"Reward Ad Is Not Loaded Yet",Toast.LENGTH_SHORT).show();
        }
    }

Whole Code

app level build.gradle file

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.programtown.example"
        minSdkVersion 17
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'

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

}

manifest file

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

    <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">
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-3940256099942544~3347511713"/>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
    >

    <Button
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Display InterstitialAd"
        android:onClick="displayInterstitialAd"
    />
    <Button
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Display Reward Video Ad"
        android:onClick="displayRewardVideoAd"
        />
    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="5"
        />
    <com.google.android.gms.ads.AdView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:id="@+id/adView"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111"
        ads:adSize="BANNER"
        xmlns:ads="http://schemas.android.com/apk/res-auto">
    </com.google.android.gms.ads.AdView>

</LinearLayout>

MainActivity.java

package com.programtown.example;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.RequestConfiguration;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.gms.ads.rewarded.RewardItem;
import com.google.android.gms.ads.rewarded.RewardedAd;
import com.google.android.gms.ads.rewarded.RewardedAdCallback;
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;

public class MainActivity extends AppCompatActivity {

    private AdView adView;
    private InterstitialAd interstitialAd;
    private RewardedAd rewardedAd;

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

        initAdmobSdk();
        initBannerAdmob();
        initInterstitialAd();
        initRewardedAd();
    }

    private void initAdmobSdk() {
        RequestConfiguration configuration =
                new RequestConfiguration.Builder().build();
        MobileAds.setRequestConfiguration(configuration);
        MobileAds.initialize(getApplicationContext(), new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });
    }

    private void initBannerAdmob() {
        adView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);
        //define any required action in listener methods
        adView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                // Code to be executed when an ad finishes loading.
            }
            @Override
            public void onAdFailedToLoad(int errorCode) {
                // Code to be executed when an ad request fails.
            }
            @Override
            public void onAdOpened() {
                // Code to be executed when an ad opens an overlay that
                // covers the screen.
            }
            @Override
            public void onAdClicked() {
                // Code to be executed when the user clicks on an ad.
            }
            @Override
            public void onAdLeftApplication() {
                // Code to be executed when the user has left the app.
            }
            @Override
            public void onAdClosed() {
                // Code to be executed when the user is about to return
                // to the app after tapping on an ad.
            }
        });
    }

    private void initInterstitialAd() {
        interstitialAd = new InterstitialAd(getApplicationContext());
        interstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
        interstitialAd.loadAd(new AdRequest.Builder().build());
        interstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                // Code to be executed when an ad finishes loading.
            }
            @Override
            public void onAdFailedToLoad(int errorCode) {
                // Code to be executed when an ad request fails.
            }
            @Override
            public void onAdOpened() {
                // Code to be executed when the ad is displayed.
            }
            @Override
            public void onAdClicked() {
                // Code to be executed when the user clicks on an ad.
            }
            @Override
            public void onAdLeftApplication() {
                // Code to be executed when the user has left the app.
            }
            @Override
            public void onAdClosed() {
                // Code to be executed when the interstitial ad is closed.
                // Load the next interstitial or you can load acc to your requirements
                interstitialAd.loadAd(new AdRequest.Builder().build());
            }
        });
    }

    private void initRewardedAd() {
        rewardedAd=loadRewardedAd();
    }

    public RewardedAd loadRewardedAd() {
        RewardedAd rewardedAd = new RewardedAd(getApplicationContext(),
                "ca-app-pub-3940256099942544/5224354917");
        RewardedAdLoadCallback adLoadCallback = new RewardedAdLoadCallback() {
            @Override
            public void onRewardedAdLoaded() {
                // Ad successfully loaded.
            }

            @Override
            public void onRewardedAdFailedToLoad(int errorCode) {
                // Ad failed to load.
            }
        };
        rewardedAd.loadAd(new AdRequest.Builder().build(), adLoadCallback);
        return rewardedAd;
    }

    public void displayInterstitialAd(View view) {
        if (interstitialAd.isLoaded()) {
            interstitialAd.show();
        } else {
            Toast.makeText(getApplicationContext(),"Interstitial Ad Is Not Loaded Yet",Toast.LENGTH_SHORT).show();
        }
    }

    public void displayRewardVideoAd(View view) {
        if (rewardedAd.isLoaded()) {
            RewardedAdCallback adCallback = new RewardedAdCallback() {
                @Override
                public void onRewardedAdOpened() {
                    // Ad opened.
                }

                @Override
                public void onRewardedAdClosed() {
                    // Ad closed.
                    // Load the next reward ad or you can load acc to your requirements
                    rewardedAd = loadRewardedAd();
                }

                @Override
                public void onUserEarnedReward(@NonNull RewardItem reward) {
                    // User earned reward.
                }

                @Override
                public void onRewardedAdFailedToShow(int errorCode) {
                    // Ad failed to display.
                }
            };
            rewardedAd.show(this, adCallback);
        } else {
            Toast.makeText(getApplicationContext(),"Reward Ad Is Not Loaded Yet",Toast.LENGTH_SHORT).show();
        }
    }
}

4) Run and test your application

Make sure you are connected to internet and then run app. If you have used real ad unit id then it will take some time to display ad on your app. However it is recommended to use test ad unit id during development to see test ad quickly and to prevent accidental click. Replace test ad unit id with real ad unit id during production.  

After Running app at the bottom banner ad will be shown.

On Display InterstitialAd button click will show Interstitial Ad

On Display Reward Video Ad button click will show Reward Ad

Conclusion

In this post we have learned how to implement Admob ads in android application.

Please Subscribe Youtube| Like Facebook | Follow Twitter


Share Post
  •  
  •  
  • 1
  • 2
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    3
    Shares

Leave a Reply

Your email address will not be published. Required fields are marked *