How to Implement Google AdMob in your Android App

November 17, 2021 Publish By : EXPERT APP DEVS 20 min read Viewed By : 189
admob integration

AdMob is a multi-platform mobile advertising network that allows you to integrate ads into your app. By implementing AdMob, you can start earning your extra income. It is very helpful particularly when you are launching a free app and you want to earn some income from it.

Integrating AdMob into your app it's an easy task. In this blog, we’ll build a simple app of two screens to display the different types of ads that Support by AdMob.

1. Type of AdMob Ads

Currently, in AdMob, we have the below types of ad units. You can choose any ad unit based on your app functionality.

➞ Banner Ad

Banner Ads fill only a part of the screen depending on the ad size that is created by you. Banner Ad comes up in multiple sizes Standard, Medium, Large, Full-Size, Leaderboard, and Smart Banner. Smart banners are very useful when you target different screen sizes and fit the same ad depending on the device's screen size.

➞ Interstitial Ad

Interstitial ads occupy the full screen of your mobile. Basically, they will be shown based on time duration, between screen transition or when the user is done some task or process. Usually, we can see these ads in games after your level completion.

➞ Rewarded Video Ad

Rewarded Video Ads are fullscreen video ads that offer some rewards points if the user watches the full ad video. Mostly these ads are used for providing rewards/coins in games.

➞ Native Ad

Native Ads provides the flexibility to set the ad appearance like color, text color, and buttons to fill like a native component of the app.

2. Creating Ad Units

1. Sign in to your AdMob account.

2. Create a new App by adding the package name of your app you want to implement AdMob. Once the App is created, you can find the APP ID on the dashboard of Admob.

3. Select the newly created App and press the ADD AD UNIT button to generate a new ad unit ID.

4. Choose your 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 AdMob dashboard. It look like ca-app-pub-066XXXXXXX/XXXXXXXXXXX

You can create many ad units as per requirement.

3. Creating New Project on Android Studio

1. Create a Fresh project in Android Studio from File - New Project. You can select Empty Activity from the Prompt, and go next.

2. Add below dependency in build.gradle file required for AdMob integration.

build.gradle
dependencies {
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:design:26.1.0' 
    compile 'ccom.google.android.gms:play-services-ads:11.8.0'
}

3. Add the App ID and Ad unit IDs to your strings.xml file. Open strings.xml located under the values folder and add the IDs of all ad units.

strings.xml
<resources>
    <string name="app_name">AdMob</string>
    <string name="title_activity_second_activiy">Interstitial</string>
    <string name="msg_welcome">Welcome to Admob. Click on the below button to launch the Interstitial ad.</string>
    <string name="btn_fullscreen_ad">Show Interstitial Ad</string>
    <string name="btn_rewarded_video">Show Rewarded Video Ad</string>
 
 
    <!-- TODO - add your ad unit Ids -->
    <!-- AdMob ad unit IDs -->
    <string name="admob_app_id">ca-app-pub-XXXXXXXX~XXXXXXXXXXX</string>
    <string name="banner_home_footer">ca-app-pub-XXXXXXXX~XXXXXXXXXXX</string>
    <string name="interstitial_full_screen">ca-app-pub-XXXXXXXX~XXXXXXXXXXX</string>
    <string name="rewarded_video">ca-app-pub-XXXXXXXX~XXXXXXXXXXX</string>
</resources>

4. Create a class with the MyApplication.java name and extend the Application class. In this application class, we have to globally apply the AdMob App Id. We can use MobileAds.initialize() method to initialize the AdMob.

(Note: App ID is not similar to Ad Unit ID. Place the App ID carefully))

MyApplication.java
import android.app.Application;
import com.google.android.gms.ads.MobileAds;
  
public class MyApplication extends Application {
 
    @Override
    public void onCreate() {
        super.onCreate();
 
        // initialize the AdMob app
        MobileAds.initialize(this, getString(R.string.admob_app_id));
    }
}

5. 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="info.androidblob.admob">
 
    <application
        android:name=".MyApplication">
 
        <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>

3.1 Adding Banner Ad

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

<com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_home_footer">
    </com.google.android.gms.ads.AdView>
    
6. Add the AdView widget in your main activity layout file (activity_main.xml). I also added a button to launch another ad in which we’ll test an Interstitial ad.
    
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="info.androidblob.admob.MainActivity">
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/msg_welcome" />
 
    <Button
        android:id="@+id/btn_fullscreen_ad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/btn_fullscreen_ad" />
 
    <Button
        android:id="@+id/btn_show_rewarded_video"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn_fullscreen_ad"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:text="@string/btn_rewarded_video" />
 
    <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"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_home_footer"></com.google.android.gms.ads.AdView>
</RelativeLayout>

7. Open MainActivity.java and paste the below code.

➞ Create an instance of AdRequest and apply the ad into AdView.

➞ Add the AdView life cycle methods in all activity life cycle method like onResume(), onPause() and in onDestroy() methods.

MainActivity.java
package info.androidblob.admob;
 
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
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.AdSize;
import com.google.android.gms.ads.AdView;
 
public class MainActivity extends AppCompatActivity {
 
    private AdView mAdView;
    private Button btnFullscreenAd, btnShowRewardedVideoAd;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        btnFullscreenAd = (Button) findViewById(R.id.btn_fullscreen_ad);
        btnShowRewardedVideoAd = (Button) findViewById(R.id.btn_show_rewarded_video);
        btnFullscreenAd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, InterstitialAdActivity.class));
            }
        });
 
        btnShowRewardedVideoAd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, RewardsVideoAdActivity.class));
            }
        });
 
        // TODO - remove this if condition
        // it's for demo purpose
        if (TextUtils.isEmpty(getString(R.string.banner_home_footer))) {
            Toast.makeText(getApplicationContext(), "Please mention your Banner Ad ID in strings.xml", Toast.LENGTH_LONG).show();
            return;
        }
 
        mAdView = (AdView) findViewById(R.id.adView);
        mAdView.setAdSize(AdSize.BANNER);
        mAdView.setAdUnitId(getString(R.string.banner_home_footer));
 
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                // Check the LogCat to get your test device ID
                .addTestDevice("JHER58FRTG25SD9RFG58B3TG52RT8G36")
                .build();
 
        mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
            }
 
            @Override
            public void onAdClosed() {
                Toast.makeText(getApplicationContext(), "Ad is closed!", Toast.LENGTH_SHORT).show();
            }
 
            @Override
            public void onAdFailedToLoad(int errorCode) {
                Toast.makeText(getApplicationContext(), "Ad failed to load! error code: " + errorCode, Toast.LENGTH_SHORT).show();
            }
 
            @Override
            public void onAdLeftApplication() {
                Toast.makeText(getApplicationContext(), "Ad left application!", Toast.LENGTH_SHORT).show();
            }
 
            @Override
            public void onAdOpened() {
                super.onAdOpened();
            }
        });
 
        mAdView.loadAd(adRequest);
    }
 
    @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();
    }
}

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

3.2 Adding Interstitial Ad (Fullscreen Ad)

Interstitial ads occupy the full screen of your mobile, For the interstitial ad doesn’t require an AdView element to the XML layout. Also, we can load the ad programmatically from the Activity or Fragment. Normally these ads will be displayed when the user is moving between activities or go to the next level when playing a game.

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

8. Create a new activity named SecondActivity.java by right-clicking on the package - New - Activity - Select Empty Activity.

SecondActivity.java
package info.androidblob.admob;
 
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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;
 
public class SecondActivity extends AppCompatActivity {
 
    private String TAG = SecondActivity.class.getSimpleName();
    InterstitialAd mInterstitialAd;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
 
        mInterstitialAd = new InterstitialAd(this);
 
        // set the ad unit ID
        mInterstitialAd.setAdUnitId(getString(R.string.interstitial_full_screen));
 
        AdRequest adRequest = new AdRequest.Builder()
                .build();
 
        // Load ads into Interstitial Ads
        mInterstitialAd.loadAd(adRequest);
 
        mInterstitialAd.setAdListener(new AdListener() {
            public void onAdLoaded() {
                showInterstitial();
            }
        });
    }
 
    private void showInterstitial() {
        if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        }
    }
}

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

3.3 Adding Rewarded Video Ad

9. Create another activity named RewardsVideoAdActivity.java and paste the below code snippet. This ad integration same as the Interstitial ad but there is a callback method onRewarded() called when there is a custom reward will get after watching the video ad completely.

RewardsVideoAdActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
 
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.reward.RewardItem;
import com.google.android.gms.ads.reward.RewardedVideoAd;
import com.google.android.gms.ads.reward.RewardedVideoAdListener;
 
public class RewardsVideoAdActivity extends AppCompatActivity {
 
    private RewardedVideoAd mRewardedVideoAd;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rewarded_video_ad);
 
        mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
        mRewardedVideoAd.setRewardedVideoAdListener(new RewardedVideoAdListener() {
 
            @Override
            public void onRewarded(RewardItem rewardItem) {
                Toast.makeText(RewardsVideoAdActivity.this, "onRewarded! currency: " + rewardItem.getType() + "  amount: " +
                        rewardItem.getAmount(), Toast.LENGTH_SHORT).show();
            }
 
            @Override
            public void onRewardedVideoAdLeftApplication() {
                Toast.makeText(RewardsVideoAdActivity.this, "onRewardedVideoAdLeftApplication",
                        Toast.LENGTH_SHORT).show();
            }
 
            @Override
            public void onRewardedVideoAdClosed() {
                Toast.makeText(RewardsVideoAdActivity.this, "onRewardedVideoAdClosed", Toast.LENGTH_SHORT).show();
            }
 
            @Override
            public void onRewardedVideoAdFailedToLoad(int errorCode) {
                Toast.makeText(RewardsVideoAdActivity.this, "onRewardedVideoAdFailedToLoad", Toast.LENGTH_SHORT).show();
            }
 
            @Override
            public void onRewardedVideoAdLoaded() {
                Toast.makeText(RewardsVideoAdActivity.this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
            }
 
            @Override
            public void onRewardedVideoAdOpened() {
                Toast.makeText(RewardsVideoAdActivity.this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
            }
 
            @Override
            public void onRewardedVideoStarted() {
                Toast.makeText(RewardsVideoAdActivity.this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
            }
        });
 
        loadRewardedVideoAd();
    }
 
    private void loadRewardedVideoAd() {
        mRewardedVideoAd.loadAd(getString(R.string.rewarded_video),
                new AdRequest.Builder().build());
 
        // showing the ad to user
        showRewardedVideo();
    }
 
    private void showRewardedVideo() {
        // make sure the ad is loaded completely before showing it
        if (mRewardedVideoAd.isLoaded()) {
            mRewardedVideoAd.show();
        }
    }
 
    @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();
    }
}

3.4 Enabling Test Ads

As per AdMob Privacy Policies, users are not allowed to click on their own live ads. In order to protect your AdMob account from getting suspended or block, use test ads during the development process as you may click the ads accidentally.

When you run the project, if you check the LogCat, you can see a similar line use. AdRequest.Builder.addTestDevice(“HJETRH48DR2T58SDR69FR5V8R23EDT38D”) to Display test ads on your Testing device. Copy the device's unique id and add it to AdRequest as per below. Note that this ID is different from device to device, By doing this, the test ads will be loaded instead of living ads.

In live mode, you need to remove addTestDevice() methods in order to load live ads.

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

3.5 Ad View Listeners

Ad listeners are very helpful to process the next action when the ad is closed or terminated by the user. The ad listeners can be used to notify your app when the ad changes its state.


mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                Toast.makeText(getApplicationContext(), "Ad is loaded!", Toast.LENGTH_SHORT).show();
            }
 
            @Override
            public void onAdClosed() {
                Toast.makeText(getApplicationContext(), "Ad is closed!", Toast.LENGTH_SHORT).show();
            }
 
            @Override
            public void onAdFailedToLoad(int errorCode) {
                Toast.makeText(getApplicationContext(), "Ad failed to load! error code: " + errorCode, Toast.LENGTH_SHORT).show();
            }
 
            @Override
            public void onAdLeftApplication() {
                Toast.makeText(getApplicationContext(), "Ad left application!", Toast.LENGTH_SHORT).show();
            }
 
            @Override
            public void onAdOpened() {
                Toast.makeText(getApplicationContext(), "Ad is opened!", Toast.LENGTH_SHORT).show();
            }
        });
        

4. Known Issues

While running the app, the Ads might not display and the given errors can be generated and seen in LogCat.

➞ There was some error in getting an ad response from an ads network. ErrorCode: 1
➞ Failed to load ad: 1

If you happen to find the above errors in your LogCat, there is no need to worry about it. The newly created Ad Units take a sometimes to display the live ad. Until then you will see these errors. The best way to resolve this problem is to wait for some time and test the app again.

If you have any queries related to android app development contact us!

Need a consultation?

Drop us a line! We are here to answer your questions 24/7.