Click here to Skip to main content
15,901,666 members
Articles / Mobile Apps / Android

Adding Google Admob Ads to Android App (Banner and Interstitial ads)

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
28 Aug 2016CPOL7 min read 29.2K   1  
Adding Google Admob Ads to Android App (Banner and Interstitial ads). Google AdMob is the most popular mobile ads platform used by app developers worldwide. Integrating AdMob to your app allows you to monetize your app and earn on the basis of Impressions and clicks on ads in your app.

Google’s AdMob is the most popular mobile ads platform used by app developers worldwide. Integrating AdMob to your app allows you to monetize your app and earn on the basis of Impressions and clicks on ads in your app. AdMob provides you tools to analyze, understand and track your audience through integration with google analytics.

It has a very flexible ad control and allows you to choose between a variety of types and sizes of the apps which can help to increase your earning through app advertising. Admob also has support for in-app purchase ads to increase the number of in-app transactions from your users.

Admob is available for Android, iOS, Unity and Cocos platform. We will be discussing the Banner and Interstitial versions of Ads which are very popular across all the ad platform.

Admob Banner vs Interstitial ads

Banners Ads are small ads which are usually displayed at the top or bottom of the screen as shown int the figure below. Standard android admob banner size is 320×50 although other sizes are also available. Banner Ads are very popular with mobile developers since they don’t interfere much with the user experience and cover very small part of the screen. However they have a low engagement rates.

Image 1

Interstitials Ads are bigger full-screen ads. They block the screen for some time until the user presses a “x” button to close the Ad. By blocking the complete screen interstitial Ads compel the user to interact with the ad, giving high user engagement and conversion rates. However these Ads if not added at proper places will often lead to frustrating user experience. Below is an example of interstitial ad.

Image 2

In this tutorial we will discuss admob integration on android using an example App. We will be creating a dummy game app consisting of two levels. Level One will show the Banner Ads and when the user clicks on the LevelTwo an Interstitial Ad will be loaded and the user will be taken to Level Two once the Ad is closed.

Before starting the discussion, please note the following:

Clicking on your own Ads to earn money is strictly against the Google AdMob’s policy, You must use the test Ads while the app is in devlopment, even if you want to test for live ads before launching your app, avoid clicking on them otherwise your Admob account might get suspended.

Pre-requisites

  1. Android Studio installed on your PC (Unix or Windows).
  2. A real time android device (Smartphone or Tablet) configured with Android Studio.

Creating a New Android Studio Project

  1. Open Android Studio and create a new project by clicking on File -> New -> New Project.
  2. Enter project name, we have used GameApp and company domain application.example.com (We have used our company domain i.e androidtutorialpoint.com. Similarly you can use yours).
  3. Click Next and choose appropriate android version.
  4. Click Next and select an Empty Activity.
  5. Choose activity name, we have named the activity as LevelOneActivity. Also make sure generate layout checkbox is checked.

This will create new android studio project. Now you are ready to montetize your new Game App.

Create your Ad Units

  1. Go to Google Admob Page and Sign-Up if you don’t have an existing account. Just Sign-In in case you already have a Google Admob Account.
  2. Click on Monetize Tab

    Image 3

  3. Click on Montetize New App button.

    Click on Monetize New App

  4. Select an App. You have three Options as shown in the fig below.
    1. You can search your app, incase you are adding admob to an existing app.
    2. Add App Manually allows to add a new app by giving a package name.
    3. Select a previously added app, if you have already added the app but didn’t follow the complete process to add admob ads.
  5. Enter your app name, select the platform as Android and click on Add app button.

    Image 5

  6. Select ad format and name the ad unit.

    Since we are adding both the banner and interstitial ads we have to make two entries one for each type of ads and save them. You can choose other options as per your requirement. We are retaining the default options.

    Image 6

    Image 7

  7. On saving the Ad unit you will get Ad unit name and Ad unit ID as shown in the figure below. Note the Ad unit ID for the two Ad units you have just created. Later we have to put these ID’s in your apps strings.xml file.

    Image 8

Add Banner and Interstitial adds to your Project

  1. Add the following dependency in your app’s build.gradle file to use the Google Admob SDK in your project.

    build.gradle

    Java
    compile 'com.google.android.gms:play-services-ads:8.4.0'
  2. Add the Ad ID for the Ad Units created earlier in the strings.xml file.

    strings.xml

    XML
    <resources>
        <string name="app_name">GameApp</string>
        <string name="interstitial_ad_sample">Interstitial Ad Sample</string>
        <string name="level_one">Level One</string>
        <string name="level_two">Level Two</string>
        <string name="ad_id_interstitial">ca-app-pub-7744357389506091/9257560120</string>
        <string name="ad_id_banner">ca-app-pub-7744357389506091/6304093723</string>
        <string name="gameHeader">My Game App</string>
    </resources>

    Replace the ad_id_interstitial and ad_id_banner with your own Ad ID’s, we have also added some other string resources which will be used in the project later.

  3. In AndroidManifest.xml add the permissions to access Internet and Network State.

    AndroidManifest.xml

    XML
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    

    Next, add the google play services meta data to the application tag. This embeds the version of Google Play services that the app was compiled with.

    XML
    <meta-data
                android:name="com.google.android.gms.version"
                android:value="@integer/google_play_services_version" />

    Also add an Ad activity to handle the config changes of your app like orientation change.

    XML
    <activity
                android:name="com.google.android.gms.ads.AdActivity"
                android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
                android:theme="@android:style/Theme.Translucent" />

    Completed AndroidManifest.xml code will be as in the following file

    AndroidManifest.xml

    XML
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.androidtutorialpoint.gameapp" >
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme" >
            <meta-data
                android:name="com.google.android.gms.version"
                android:value="@integer/google_play_services_version" />
            <activity android:name=".LevelOneActivity" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity
                android:name="com.google.android.gms.ads.AdActivity"
                android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
                android:theme="@android:style/Theme.Translucent" />
        </application>
    
    </manifest>
  4. Open the layout file activity_level_one.xml and add the following code to it.

    activity_level_one.xml

    XML
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context=".LevelOneActivity">
    
        <TextView android:id="@+id/game_text_view" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:layout_centerHorizontal="true"
            android:layout_marginTop="50dp" android:text="@string/gameHeader"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    
        <TextView android:id="@+id/level_text_view" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:layout_below="@id/game_text_view"
            android:layout_centerHorizontal="true" android:text="@string/level_one"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    
        <Button android:id="@+id/level_two_button" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:layout_centerHorizontal="true"
            android:layout_centerVertical="true" android:text="@string/level_two" />
    
        <!-- view for AdMob Banner Ad -->
        <com.google.android.gms.ads.AdView android:id="@+id/banner_AdView" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:layout_centerHorizontal="true"
            android:layout_alignParentBottom="true" ads:adSize="BANNER"
            ads:adUnitId="@string/ad_id_banner" />
    </RelativeLayout>

    Here we are using a Relative Layout as a parent layout. We have a TextView to display a static message “My Game App”, Next we have a TextView to display the current level of the game. We only have two Levels – Level One and Level Two.

    Then we have a button that will take us to Level Two. At the end we have a Google Admob Adview which will be used to display the Banner Ads at the bottom of the your app Screen as discussed in starting. We have added the adUnitId for the banner Ad using our ad_id_banner string resource. For Banner Ads adSize has a value of Banner.

  5. Open LevelOneActivity.java and create private variables for the Level Two Button, InterstitialAd, Level TextView and also the Banner AdView.

    LevelOneActivity.java

    Java
    private Button mLevelTwoButton;
    private InterstitialAd mInterstitialAd;
    private TextView mLevelTextView;
    private AdView mBannerAd;

    In the onCreate() method of LevelOneActivity intialize add the reference to the buttons and views. Also add an OnClickListener() for the Level Two Button and explicitly enable it on start of the activity.

    Java
     // Create the next level button, which tries to show an interstitial when clicked.
     mLevelTwoButton = ((Button) findViewById(R.id.level_two_button));
     // Load the add into Admob banner view.
     mBannerAd = (AdView) findViewById(R.id.banner_AdView);
     // Text view to show the level number.
     mLevelTextView = (TextView) findViewById(R.id.level_text_view);
    
    mLevelTwoButton.setEnabled(true);
     mLevelTwoButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
             showIntAdd();
         }
     });
    

    Next Create and Load a new Interstitial Ad and then load Banner Ads. For now just put the following methods in onCreate() method of the LevelOneActivity.java, we will be explaining these methods next.

    Java
    // Creating and load a  new InterstitialAd .
    mInterstitialAd = createNewIntAd();
    loadIntAdd();
    
    //Load BannerAd
    showBannerAd();
    

    The showBannerAd() method builds a new adRequest using the AdRequest.Builder() method and then the request is loaded to the Banner AdView we added to the layout File, Please note the use of addTestDevice(“754DB6521943676637AE86202C5ACE52”) method in the method. As we have discussed in the beginning the app developer should not click on his own live ads. To prevent your Admob account from being suspended you should always work with the test ads. When you run your the LogCat output will show you the TestDeviceId for your device as shown in the figure below.

    Replace the TestDeviceId in the showBannerAd() method with your own device Id.

    Image 9

    Be sure to remove the TestDeviceId before going live with your app.

    Add the following methods after onCreate() method of the LevelOneActivity.java.

    Java
    private void showBannerAd() {
           AdRequest adRequest = new AdRequest.Builder()
                   .addTestDevice("754DB6521943676637AE86202C5ACE52")
                   .build();
           mBannerAd.loadAd(adRequest);
    
       }
    

    Also add createNewIntAd() method after the showBannerAd(), This method creates a new Interstitial Ad and also sets the AdUnitId and setAdListener property of the new Interstitial Ad. In the AdListener we have are enabling the LevelTwoButon once the Ad is loaded and also in the case that Ad fails to load. Once the user closes the Ad the Game proceeds to level two by calling the function levelTwo() .

    Java
    private InterstitialAd createNewIntAd() {
            InterstitialAd intAd = new InterstitialAd(this);
            // set the adUnitId (defined in values/strings.xml)
            intAd.setAdUnitId(getString(R.string.ad_id_interstitial));
            intAd.setAdListener(new AdListener() {
                @Override
                public void onAdLoaded() {
                    mLevelTwoButton.setEnabled(true);
                }
    
                @Override
                public void onAdFailedToLoad(int errorCode) {
                    mLevelTwoButton.setEnabled(true);
                }
    
                @Override
                public void onAdClosed() {
                    // Proceed to the next level.
                    levelTwo();
                }
            });
            return intAd;
        }

    Next, Add the following code in LevelOneActivity after the above methods. The showIntAdd() checks whether the add has been loaded and if it is available then it displays the Ad otherwise it displays the next level of the game. The loadIntAdd() will disable the level two button and then create a new adRequest similar to showBannerAd() method and then loads the request in the AdView. The levelTwo() invokes the second level of our game, here we are just making the button disappear and changing the level text to display Level Two.

    Java
    private void showIntAdd() {
           
    // Show the ad if it's ready. Otherwise toast and reload the ad.
            if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
                mInterstitialAd.show();
            } else {
                levelTwo();
            }
        }
        private void loadIntAdd() {
            // Disable the  level two button and load the ad.
            mLevelTwoButton.setEnabled(false);
            AdRequest adRequest = new AdRequest.Builder()
                    .addTestDevice("754DB6521943676637AE86202C5ACE52")
                    .build();
            mInterstitialAd.loadAd(adRequest);
        }
    
    
        private void levelTwo() {
            // Show the next level
            mLevelTwoButton.setVisibility(View.INVISIBLE);
            mLevelTextView.setText("Level Two");
            Toast t = Toast.makeText(this,"You have reached Level Two !!",Toast.LENGTH_LONG);
            t.show();
            }

Now, run the app on your phone or emulator and you should see Banner Ad at the bottom of the screen and Interstitial Ad on clicking Level Two Button.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Hello Developer!

As a co-founder, I would like to welcome you to the Android Tutorial Point community!. I hope you get the best possible value at of our platform. Stick with us for a while, and we promise you will become an $$Android Rockstar$$!

Android Tutorial Point is the right platform if you want to learn about android development. We have a broad collection of tutorials on different aspects of Android Development and it is growing rapidly. Here at Android Tutorial Point we thrive to deliver the best tutorials. In this direction, we are trying to create a community that will cater to your needs, whether you are a beginner or a seasoned veteran. For the beginners that are getting started on Android Development
journey, we would suggest you to begin with our Android Basics Tutorial available at http://www.androidtutorialpoint.com/category/basics/ . Here, we feature articles on how to start with Android programming.


All the best from the Android Tutorial Point team. Don't forget to subscribe our blog for latest android tutorials. You can reach out to us at our Facebook page https://www.facebook.com/androidtutorialpoint/ or Add us on Twitter https://twitter.com/androidtutpoint/ . Any ideas or suggestions? Shoot us an email at androidtutorialspoint@gmail.com

Comments and Discussions

 
-- There are no messages in this forum --