Tek Eye Logo

Tek Eye

AdMob Ad Incorporated into an Android Activity

Displaying advertisements (ads) is one way of monetizing an app. To monetize (monetise) something is to turn it into cash. That term applied to apps and web pages and refers to getting revenue through ads or paid content. Showing ads is one way of generating an income for the time and effort spent developing the app. Though a reasonably successful app is required to generate worthwhile funds. Other techniques include charging a price for the app and providing additional content within the app for a fee, i.e. In-App Billing.

Android Logo

A Tutorial on Adding an AdMob Ad to an Android App

Google makes it relatively easy to include ads in an app, as the example code in this tutorial will show. This AdMob demo should help those who may have found it difficult to get the example provided with the online AdMob documentation to work. All the steps required to get an ad served in your app are covered. So read on to find out how to add AdMob to Android apps.

(For this Android tutorial try the code in a simple app. This article assumes that the latest Android Studio is installed, a basic app can be created and run, and the code in this article can be correctly copied into Android Studio. The example code can be changed to meet your own requirements. When entering code in Studio add import statements when prompted by pressing Alt-Enter.)

List of Steps to Get an AdMob Banner Ad Started

Here is a summary of the steps covered by this AdMob demo tutorial:

  • Getting an AdMob account
  • Targeting the correct Android version
  • Linking to the AdMob code
  • Get all the AdMob ids required
  • Initialising the Admob ad code
  • Implementing an AdMob ad
  • Adding the AdView to the screen
  • Calling the ad loading code

Get an AdMob Account

When a device is running your app, you will get a very small payment for each ad that is selected (clicked or pressed on), and a small payment for so many thousands of ad impressions (displayed ads). In order for Google to make that payment it must identify in which app the ad was placed. This is done by placing a unique Publisher Id in the code that is showing the ads. To get the unique id for each app you need an AdMob account. Head over to https://www.google.com/admob/ and sign up, you will need a Google account to register.

Target SDK is API 14 (Android Ice Cream Sandwich) or Higher

It is assumed your app is ready for publishing, lets put in the ad serving code so that when you activate it on Google Play it can (potentially) make you some money. In this tutorial the code is added to an existing example project, in this case the simple starting Hello World! basic app. You can follow this tutorial using the basic starting app, or your own app.

When developing an app use the latest Android API Software Development Kit (SDK) available and, according to the documentation, it must be at least Android 4.0.1 (API Level 14). Here Android 8.1 (API Level 27) was selected, the latest available at the time of writing.

Add the Google Play Services AdMob Library to the App

The AdMob library is part of the Google Play Services. Open the build.gradle file for the app (Module: app) and in the dependencies section add the Play Services Ads dependency using the implementation directive. Always reference the latest version of the Play Services Ads, which at the time of updating this article was version 15.0.1, i.e. implementation 'com.google.android.gms:play-services-ads:15.0.1', see the Google APIs for Android Release Notes:

AdMob Reference in Studio

With the Play Services referenced a Gradle sync message will be displayed. Click the link to perform the sync.

(Depending upon the version of Studio and Android SDK installed other libraries may need updating with the relevant additional implementation directives. A message will be displayed stating which library needs updating. To view the external libraries use the dropdown at the top of the Project explorer and select Project, then expand External Libraries.)

Linking the App to the Google Repository

The latest versions of Studio will come with the latest versions of Gradle. Projects created in the latest version of Studio automatically reference the Google online compiled library repositories. This is done via the top level build.gradle file (not the one in the app folder).

Google Repository Reference

(In earlier versions of Studio the google() entry was not supported and an entry of maven { url "https://maven.google.com" } needed to be provided.)

Get the App Ad Ids or Use the Test Ids

To advertise using the Google AdMob platform various ids are required by the app. The ids will be embedded into the app serving up the ad. There is the AdMob Publisher Id which is assigned when the AdMob account is created. The app will also require an AdMob app id, then each ad unit will also have an ad id. For testing purposes Google provides test ids that allow the apps with ad code to run without violating Google's AdMob policies, useful during the development phase of an app project. For more information on obtaining the various AdMob ids required and how to generate them see the Tek Eye article AdMob App Id and Ad Id for Android.

Initialise the Ads Code

The Mobile Ads SDK needs initialising with a call to MobileAds.initialize passing in the app id (see Ids section above). Here is the code to initialise MobileAds for the example Hello World app used here (use the Alt-Enter keys to add the import to com.google.android.gms.ads.MobileAds when prompted by Studio). This code is shown using the test app id of ca-app-pub-3940256099942544~3347511713 which will need replacing with your app id for production testing:

package com.example.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

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

public class MainActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {

        // Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713
        // TODO: Replace sample app ID with your AdMob app ID
        MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");

Implement an Ad

The MobileAds SDK supports several types of ads:

  • Banner - An ad occupying some space on the currently shown app screen
  • Interstitial - A full screen ad that can be shown between app screens at appropriate points.
  • Native - At time of writing the Native ad format is in beta testing. It will allow for ads that can be customised to fit in with the look and feel of your app for a less jarring app feel.
  • Video - A full screen video can be used to implement a reward mechanism in an app. For example a game app could use the video add to reward the player an extra life for watch and ad.

Adding the View for the Banner Ad (AdView)

To implement a banner ad the space for the ad needs setting up in the apps layout screen. This can be done by adding an AdView to the app screen's layout file, here the layout file is called activity_main.xml. This can be done with drag and drop from the Palette. Though adding the correct code to the layout XML via the Text tab can sometimes be easier.

AdView in an Android Activity

If using the default ConstraintLayout, as used in this example, then put in and adjust contraints as required. The AdView will require the adSize and adUnitId attributes. With adSize set to BANNER and adUnitId set to the defined ad unit id for the given ad. For pre-production testing use the test AdMob banner id (ad unit id) of ca-app-pub-3940256099942544/6300978111. Here is the layout code used in this example:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

        app:adUnitId="ca-app-pub-3940256099942544/6300978111" />

        android:text="Hello World!"
        app:layout_constraintTop_toBottomOf="@+id/adView" />


Implementation of the Banner Ad Loading Code

With the AdMob library linked to the app, and the AdView defined on the screen, the final step is to load an ad in the code. this is done via a call to loadAd passing in an AdRequest. Here is the code added to the MainActivity.java file used in this example:

package com.example.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
//Imports for AdMob
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;

public class MainActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {

        // Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713
        // TODO: Replace sample app ID with your AdMob app ID
        MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");
        //Load the add
        AdRequest adRequest = new AdRequest.Builder().build();

When this simple AdMob demo app runs the AdMob test banner ad is displayed:

Android Test Ad Running

That is the basic funtionality for an AdMob ad running in a Android app. For more advance control see the additional ad events that can be hooked into, in the AdMob documentation. Don't forget to change all the test ids for the production ids before your app is shipped.

See Also

Archived Comments

KINJAL on February 18, 2014 at 5:56 am said: I am a bit confused on how I get the Publisher Id before I post it on Google Play. I have my app completed, but haven't posted it anywhere on the Internet. I want to post it only on Google Play but with ads from AdMob. So how do I get a publisher id before uploading it on Google Play. Its more like a chicken and the egg problem. Am I missing something here?

Tek Eye on February 18, 2014 at 10:30 pm said: It does seem that way. However you can manually add an App in AdMob to generate the ad unit id. Note that this article covers the deprecated method of adding ads to Apps. Use the new Google Play library, see https://developers.google.com/admob/ Update: This article has been updated (see the update date at the end of the article) to cover the current version of AdMob. See the Tek Eye article AdMob App Id and Ad Id for Android.

Author:  Published:  Updated:  

ShareSubmit to TwitterSubmit to FacebookSubmit to LinkedInSubmit to redditPrint Page

Do you have a question or comment about this article?

(Alternatively, use the email address at the bottom of the web page.)

 This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

markdown CMS Small Logo Icon ↓markdown↓ CMS is fast and simple. Build websites quickly and publish easily. For beginner to expert.

Articles on:

Android Programming and Android Practice Projects, HTML, VPS, Computing, IT, Computer History, ↓markdown↓ CMS, C# Programming, Using Windows for Programming

Free Android Projects and Samples:

Android Examples, Android List Examples, Android UI Examples

Tek Eye Published Projects