Android August 9, 2019 7 min read

How To Use Google AdMob effectively in Android Applications

We all want to earn money through our mobile application as soon as they launch. Probably, the best to earn is to use Google AdMob in the…

We all want to earn money through our mobile application as soon as they launch. Probably, the best to earn is to use Google AdMob in the application as they are reliable and trustworthy.

Before getting into the codes, let’s review some of the policy so that our account and application are safe from policy violations.

Few Policy Violations prevention to keep in mind before integrating Google AdMob into your application —

BANNER AD —

When implementing a banner ad make sure,

INTERSTITIAL AD —

When implementing an interstitial ad take care of,

REWARDED VIDEO AD —

When using Reward Video Ad,

Enough of the policies, let us look into the code implementation now,

IMPLEMENTATION

First, include the dependencies in your Android Project.

In the Project Level Build.Gradle

allprojects {
    repositories {
        google()
        jcenter()
    }
}

In the Application Level Build.Gradle, add the following dependency

dependencies {
    implementation 'com.google.android.gms:play-services-ads:18.1.1'
}

The most important part is to include the APPLICATION_ID in the Android Manifest. You can get the Application ID form your Google AdMob by,

Apps -> Select the application -> App Settings -> App ID.

Add it in your manifest within the <application> tag.

<meta-data
    android:name="com.google.android.gms.ads.APPLICATION_ID"
    android:value="YOUR_ADMOB_APP_ID"/>

You can use sample AdMob App ID —

ca-app-pub-3940256099942544~3347511713

Another optional step is to initialize the AdMob SDK. This is not a necessary step but using this will help in loading the first Ad sooner. If not done, the first Ad Request from the application will do the work of initializing.

MobileAds.initialize(this,"ca-app-pub-3940256099942544~3347511713");

BANNER AD—

For implementing Banner Ad, the best position is to keep it at the bottom of the activity. There are three ways to do so,

Add a view in the XML of the activity as —

<RelativeLayout
android:id="@+id/adMobView"        android:layout_width="match_parent"        android:layout_height="60dp"        app:layout_constraintBottom_toBottomOf="parent"/>

In the Java side, add the following code —

View adContainer = findViewById(R.id.adMobView);
AdView mAdView = new AdView(getApplicationContext());                mAdView.setAdSize(AdSize.FULL_BANNER);
mAdView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
mAdView.loadAd(adRequest);

2. Adding it dynamically through Java code —

The Banner Ad can be added dynamically through the Java Code —

LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
// Create a banner ad
AdView mAdView = new AdView(this);
mAdView.setAdSize(AdSize.SMART_BANNER);
mAdView.setAdUnitId("myAdUnitId");
// Create an ad request.
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
// Optionally populate the ad request builder.
adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
// Add the AdView to the view hierarchy.
layout.addView(mAdView);
// Start loading the ad.
mAdView.loadAd(adRequestBuilder.build());
setContentView(layout);

3. Add it directly through the XML code —

<com.google.android.gms.ads.AdView
            xmlns:ads="http://schemas.android.com/apk/res-auto"
            android:id="@+id/adView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_alignParentBottom="true"
            ads:adSize="BANNER"
            ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
</com.google.android.gms.ads.AdView>

Interestingly, an AdView Listener can be used as —

mAdView.setAdListener(new AdListener() {                     @Override                    
public void onAdLoaded() {                                
}                   
Override                    
public void onAdFailedToLoad(int errorCode) {  
}              
@Override
public void onAdOpened() {
}
@Override
public void onAdClosed() {
}
@Override
public void onAdLeftApplication() { 
}  
});

One intelligent work can be, keeping the view hidden initially and when onAdLoaded() is invoked on successful Ad loading, the view can be shown to the user.

You can different kindof banner as mentioned here — https://developers.google.com/admob/android/banner

INTERSTITIAL AD —

Keeping in mind the policies of the AdMob Interstitial Ad, it can be implemented as follows. We can do this as —

private InterstitialAd mInterstitialAd;
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub 3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
    @Override
    public void onAdLoaded() {
        // Code to be executed when an ad finishes loading.
        mInterstitialAd.show();
}

    @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.
    }
});

A sample use case of the interstitial ad is switching between the activity. This can be done as —

if (mInterstitialAd != null){
   if (mInterstitialAd.isLoaded()) {            
          mInterstitialAd.show();                  
          mInterstitialAd.setAdListener(new AdListener() {                    
          @Override
          public void onAdClosed() {                       
              //TODO: Intent
          }
         });
   } else {
      //TODO: Intent
} else {
  //TODO: Intent
}

This will ensure that no policy violation is done as it will only fire the Intent on successful closing or when it is not loaded then it will directly open. For this, also init and load the Interstitial Ad in either OnResume() or OnCreate().

REWARDED VIDEO AD —

A rewarded video can be implemented as follows —

private RewardedVideoAd mRewardedVideoAd;
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",
            new AdRequest.Builder().build());

For checking if the Ad has been loaded,

if (mRewardedVideoAd.isLoaded()) {
    mRewardedVideoAd.show();
}

A Rewarded Video Ad Listener is implemented as,

mRewardedVideoAd.setRewardedVideoAdListener(new RewardedVideoAdListener() {
@Override
public void onRewarded(RewardItem reward) {
    // Reward the user.
}

@Override
public void onRewardedVideoAdLeftApplication() {
}

@Override
public void onRewardedVideoAdClosed() {
}

@Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {
}

@Override
public void onRewardedVideoAdLoaded() {
if (mRewardedVideoAd.isLoaded()) {
           mRewardedVideoAd.show();
     }
}

@Override
public void onRewardedVideoAdOpened() {
}

@Override
public void onRewardedVideoStarted() {
}

@Override
public void onRewardedVideoCompleted() {
}
});

To maintain the Lifecycle, you can use these in the specified functions —

@Override
public void onResume() {
    mRewardedVideoAd.resume(this);
    super.onResume();
}

@Override
public void onPause() {
    mRewardedVideoAd.pause(this);
    super.onPause();
}

@Override
public void onDestroy() {
    mRewardedVideoAd.destroy(this);
    super.onDestroy();
}

CONCLUSION —

All these are test Ad IDs which will show Test Ads on successful implementation. Replace these Ad IDs with your Real Ad IDs before launching the application to production. For a little tweet, you can fetch the Ad IDs from the server and set the Ad Unit ID through SharedPreferences.

The Google AdMob SDK occupies nearly 0.8 MB in the production AAB which can be reduced to 0.1 MB using Google AdMob Lite SDK. Make sure you use the Lite SDK to keep your app size as low as possible.

dependencies {
    implementation 'com.google.android.gms:play-services-ads-lite:18.1.1'
}

Another important thing to note is that, when using AdMob Ads and publishing your application through Playstore, you would need a privacy policy link inside your application as well as in the Store listing section. If not, Google will be ready to unpublish your application within 2 weeks of the launch date.

  1. Do not place multiple banner ads in a single activity.
  2. Keep a check on the lifecycle of the activity and destroy the banner when the activity is destroyed and load when the activity is visible.
  3. Separate the banner ad with the content of the activity so that there is a visible difference between both (to avoid unnecessary and mistaken clicks).
  1. An interstitial ad should be placed between two screens.
  2. An interstitial should not popup before the application is opened or after the application is closed. The ad should be displayed only within the scope of the application— For this, once the application is visible show the interstitial ad and before the application is closed (using the back button) show an interstitial and on closing, show an alert asking if the user wants to exit. By doing so, the content of the screen changes and hence no policy is violated.
  3. When in a screen, do not show interstitial ad which when closed displays the same content.
  1. Do not implement reward video ad if your application has real cash payouts.
  2. Do not ask your users to click/view the ad with ‘support us’.
  3. A reward ad should be displayed only when the user has agreed to view it.
  4. Do not offer a random reward to the user and declare it beforehand. Do not fail to give the reward on successful completion.
  5. State the reward clearly to the users (e.g., “View this ad to receive 100 gold coins” or “View this ad to receive a Sword of Slaying”).
  6. The reward must be redeemable from within the application.
  1. Add a View and Load it through Java Code