Home » Android » Android How to Integrate Google AdMob in your App

Android How to Integrate Google AdMob in your App

AdMob is a multi platform mobile ad network that allows you to monetize your android app. By integrating AdMob you can start earning right away. 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 we’ll build a simple app with two screen to show the different types of ads that AdMob supports.

android-integrating-admob-ad-platform-earn-money


1. Type of AdMob Ads

AdMob currently offers below types of ad units. You can choose the ad format depending on your app criteria.

> Banner Ad
Banner Ads occupies only portion of the screen depending on the ad size that is created. 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 and fit the same ad depending on the screen size.

> Interstitial Ad
Interstitial ads occupies full screen of the app. 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.

> Native Express (Deprecated)
Starting March 1, 2018 the Native Express ads will be discontinued.

> Native Advanced (Beta)
Native Advanced ads are still in Beta program and not available to everyone. This article will be updated once the feature is available publicly.

android-integrating-admob-banner-interstitial

2. Creating Ad Units

Note: AdMob admin interface changes quite often. The below steps to create Ad Unit IDs might differ time to time.

1. Sign into your AdMob account.

2. Create a new App by giving the package name of the app you want to integrate AdMob. Once the App is created, you can find the APP ID on the dashboard which looks like ca-app-pub-XXXXXXXXX~XXXXXXXXX.

3. Select the newly created App and click on ADD AD UNIT button to create a new ad unit.

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 look like ca-app-pub-066XXXXXXX/XXXXXXXXXXX

Create as many ad units required for your app.

android-admob-creating-ad-unit

3. Creating New Project

1. Create a new project in Android Studio from File ⇒ New Project. When it prompts you to select the default activity, select Empty Activity and proceed.

2. Open build.gradle and add play services dependency as AdMob requires it.

compile ‘com.google.android.gms:play-services-ads:11.8.0’

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    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. Open strings.xml located under res ⇒ values and add the IDs of all the ad units.

    AdMob
    Interstitial
    Welcome to Admob. Click on the below button to launch the Interstitial ad.
    Show Interstitial Ad
    Show Rewarded Video Ad


    
    
    ca-app-pub-XXXXXXXX~XXXXXXXXXXX
    ca-app-pub-XXXXXXXX~XXXXXXXXXXX
    ca-app-pub-XXXXXXXX~XXXXXXXXXXX
    ca-app-pub-XXXXXXXX~XXXXXXXXXXX

4. 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.

(Note: App ID is different from Ad Unit ID. Place the App ID carefully)

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

/**
 * Created by ravi on 25/12/17.
 */

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 tag to execute the class on app launch.




    

        
            
                

                
            
        
    

3.1 Adding Banner Ad

Banner ads occupies 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.

    

6. 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 in which we’ll try Interstitial ad.




    

    

7. Open MainActivity.java and modify the code as shown.

> Create an instance of AdRequest and load the ad into AdView.

> Ad the AdView life cycle methods in onResume(), onPause() and in onDestroy() methods.

package info.androidhive.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, RewardedVideoAdActivity.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("C04B1BFFB0774708339BC273F8A43708")
                .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 the app, you should see a banner ad at the bottom of your screen.

android-displaying-admob-banner-ad

3.2 Adding Interstitial Ad (Fullscreen Ad)

Interstitial ads occupies full screen of the app. Adding interstitial ad doesn’t require an AdView element to be added in the xml layout. Rather we load the ad programatically from the activity. Normally these ads will be populated when user is moving between activities or moving to next level when playing a game.

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

8. Create an activity named SecondActivity.java by right clicking on package New ⇒ Activity ⇒ Empty Activity.

package info.androidhive.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 launched.

android-displaying-admob-interstitial-ad

3.3 Adding Rewarded Video Ad

9. Create another activity named RewardedVideoAdActivity.java and add the below code. This is same as Interstitial but there will be a callback method onRewarded() called when there is a reward after watching the video ad completely.

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 RewardedVideoAdActivity 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(RewardedVideoAdActivity.this, "onRewarded! currency: " + rewardItem.getType() + "  amount: " +
                        rewardItem.getAmount(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onRewardedVideoAdLeftApplication() {
                Toast.makeText(RewardedVideoAdActivity.this, "onRewardedVideoAdLeftApplication",
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onRewardedVideoAdClosed() {
                Toast.makeText(RewardedVideoAdActivity.this, "onRewardedVideoAdClosed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onRewardedVideoAdFailedToLoad(int errorCode) {
                Toast.makeText(RewardedVideoAdActivity.this, "onRewardedVideoAdFailedToLoad", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onRewardedVideoAdLoaded() {
                Toast.makeText(RewardedVideoAdActivity.this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onRewardedVideoAdOpened() {
                Toast.makeText(RewardedVideoAdActivity.this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onRewardedVideoStarted() {
                Toast.makeText(RewardedVideoAdActivity.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 Policies you are not allowed to click on your own live ads. In order to protect your AdMob account from getting suspended, use test ads during development as you might click the ads accidentally.

When you run the project, if you monitor the LogCat, you can find a similar line Use AdRequest.Builder.addTestDevice(“C04B1BFFB0774708339BC273F8A43708”) to get test ads on this device. Copy the device id and add it to AdRequest as shown below. Note that this ID varies from device to device, By doing this, the test ads will be loaded instead of live ads.

In production you need to make sure that you removed addTestDevice() methods in order to render the live ads and start monetization.

AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                // Check the LogCat to get your test device ID
                .addTestDevice("C04B1BFFB0774708339BC273F8A43708")
                .build();

3.5 Ad View Listeners

Ad listeners are very useful to perform the next action when ad is closed. Below are the ad listeners can be used to notify your app when 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 below errors can be seen in LogCat.

> There was a problem getting an ad response. ErrorCode: 1
> Failed to load ad: 1
If you happen find the above errors in your LogCat, there is no need worry. The newly created Ad Units takes few hours to display the actual ad. Until then you will see these errors. The best way to resolve this problem is to wait for few hours and test the app again.

Change Log

Updated On 25th Dec, 2017 (Content Update, Latest Ad Formats)
Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info
Tags:

Leave a Reply

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