Get Started in Android Studio

This guide shows you how to integrate the Google Mobile Ads SDK into a brand new app and use it to display an AdMob banner ad. It takes about thirty minutes to complete and gives you a good sense of how the SDK functions within an app. If you're new to Google Mobile Ads, this is a great place to start before moving on to more advanced examples.

The ad unit and samples that we provide return test ads. Test ads are always available, even if your account is suspended or disabled. For more information, review the AdMob policies and learn more about invalid activity.

It is against AdMob policy to click on your own live ads. During development and testing, use only test ads. If you do need to render live ads before launch, avoid clicking on them. If you click on live ads, your AdMob account may be suspended.

No two developers have the same level of experience, so we've added occasional notes like this one for those who are new to Android and Android Studio. If you're an expert, feel free to skip them.

Prerequisites

  • Running Android Studio 1.0 or higher
  • Developing for Android level 9 or higher
  • An Android Studio project

To complete the Get Started guide, you need to have Android Studio installed on your development machine. If you don't already have it, see the Android Studio site for instructions on how to download everything you need to get up and running.

If you haven't used Android Studio before, consider running through the Building Your First App tutorial for Android Studio before starting this one.

Integrate the Mobile Ads SDK

Verify app-level build.gradle (excerpt)

...
    dependencies {
            compile fileTree(dir: 'libs', include: ['*.jar'])
            compile 'com.android.support:appcompat-v7:xx.x.x'
            compile 'com.google.android.gms:play-services-ads:10.0.1'
        }

Add the line in bold above into your app-level build.gradle.

  1. If you see a warning message across the top of the Android Studio window indicating that Gradle needs to perform a sync, click Sync Now. Gradle refreshes your project's libraries to include the dependency you just added.

  2. If you see a message asking you to install the Google Repository, just agree to the install and have Android Studio take care of the download for you. The Google Repository contains code for Gradle to incorporate.

  3. Once your build.gradle files are modified and everything has synced, try rebuilding your project (Run app in the Run menu) to make sure it compiles correctly.

You won't see any changes, but including the Mobile Ads SDK is the first step toward getting ads into your app.

An ad unit ID is a unique identifier given to the places in your app where ads are displayed. Create an ad unit for each activity your app will perform. If you have an app with two activities, for example, each displaying a banner, you need two ad units, each with its own ID. AdMob ad unit IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX/NNNNNNNNNN.

For your new app to display an ad, it needs to include an ad unit ID. Open your app's string resource file, which is found at BannerExample/app/src/main/res/values/strings.xml.

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">My Application</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="banner_ad_unit_id">ca-app-pub-3940256099942544/6300978111</string>
</resources>

Add a new <string> tag as shown. Note that the ad unit ID provided above is just for testing. It allows you to retrieve a sample banner ad and make sure your implementation is correct. You should always use test ads when developing and testing your app. It is against AdMob policy to click on your own live ads. During development and testing, use only test ads. If you do need to render live ads before launch, avoid clicking on them. If you click on live ads, your AdMob account may be suspended. See the Test ads section of the Targeting guide for information on how to get test ads with your own ad unit IDs.

While it's not a requirement, storing your ad unit ID values in a resource file is a good practice. As your app grows and your ad publishing needs mature, it may be necessary to change the ID values. If you keep them in a resource file, you never have to search through your code looking for them.

Place an AdView in your main activity layout

Layout files contain XML definitions for the visual design of things like activities, fragments, and list items. Modify the layout file for the main activity so that it includes an AdView at the bottom. You can add things to an activity programmatically via Java code, but layout files offer better separation of presentation and behavior.

For your app to show an ad, you need to modify your main activity's layout to include an AdView:

  1. Open the BannerExample/app/src/main/res/layout/activity_main.xml file:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            xmlns:ads="http://schemas.android.com/apk/res-auto"
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            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=".MainActivity">
             
            <TextView android:text="@string/hello_world"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
             
            <com.google.android.gms.ads.AdView
                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="@string/banner_ad_unit_id">
            </com.google.android.gms.ads.AdView>
             
    </RelativeLayout>

  2. Add an additional namespace to be used for ads:

    http://schemas.android.com/apk/res-auto
    
  3. Add a new element for your AdView.

  4. Set layout_width and layout_height to wrap_content.

  5. In the AdView tag, set the adSize to BANNER and the adUnitId to @string/banner_ad_unit_id.

If you look at the last parameter in the AdView tag, you can see that it's called adUnitId. This is the ad unit ID that the AdView uses when requesting ads. In this case, we've given it a reference to the string resource you added in the last step, so the AdView uses that value.

Initialize the Google Mobile Ads SDK

To initialize the Google Mobile Ads SDK at app launch, call MobileAds.initialize() in the onCreate() method of the MainActivity class with your application ID:

MainActivity.java (excerpt)

package ...

import ...
import ...

public class MainActivity extends ActionBarActivity {

    ...

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

    ...

}

Initializing the Google Mobile Ads SDK at app launch allows the SDK to fetch app-level settings and perform configuration tasks as early as possible, which can help reduce latency for the initial ad request. Initialization requires an Application context or Activity context, and an app ID. App IDs are unique identifiers given to mobile apps when they're registered in the AdMob console. If you just want to try out AdMob and don't already have an app ID, you can use the app ID in the example above.

To find your app ID, click the App management option under the settings dropdown (located in the upper right-hand corner) on the AdMob account page. App IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX~NNNNNNNNNN.

Load the ad in the MainActivity class

The last change needed is for you to add to your app's main activity class some Java code that loads an ad into the AdView, as follows.

MainActivity.java (excerpt)

package ...

import ...
import ...
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

public class MainActivity extends ActionBarActivity {

    ...

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

        AdView mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
    }

    ...

}

The two new sections of code shown above do the following:

  1. Import the AdRequest and AdView classes.

  2. Find your AdView in the layout, create an AdRequest, and then load an ad into the AdView with it.

Do not use the AdRequest line shown above if you are testing. See the Test ads section of the Targeting guide to learn more about using test devices and test device IDs.

Once that's completed, you're finished. You now have a fully functional AdView in your app's main activity.

Enjoy a freshly loaded ad

Your app is now ready to display an ad using the Google Mobile Ads SDK. Run it again and see a test banner displayed at the bottom of the device screen:

Congratulations! You've successfully integrated banner ads into an app.

See the finished example on GitHub

Download BannerExample

What's next

  1. Sign up for an AdMob account and create your own app and banner ad unit and use it with the example you just created. Remember to configure your app for test ads to avoid generating false impressions.
  2. AdMob is integrated with Firebase. You may optionally upgrade your app to use Firebase to take advantage of Analytics and other Firebase services. The rest of AdMob's documentation lives on firebase.google.com, but its content is still relevant even if you choose not to upgrade to Firebase.
  3. AdMob has more formats than just banner ads! Check out the Interstitial, Rewarded Video, and Native Ads Express guides to learn more about these ad formats.

FAQ

My app doesn't show an ad when I run it, and I see "Not enough space to show ad" in the log. What's going on?
It sounds like you're testing the app on a device with a screen that's 320dp wide. With the default padding for the activity (16dp), there's not enough space to show a 320x50 test banner. Try removing the android:paddingRight and android:paddingLeft attributes from the RelativeLayout in activity_main.xml, and then recompiling the app.
I see onPause(), onResume(), and onDestroy() in the download. What are these?
These are the AdView lifecycle methods. They allow you to pause, resume, and destroy the webview, as appropriate, when the user leaves the app (by clicking an ad), returns to the app, or leaves the current activity.
Do I need to use test ads?
Yes. It is against AdMob policy to click on your own live ads. During development and testing, use only test ads. If you do need to render live ads before launch, avoid clicking on them. If you click on live ads, your AdMob account may be suspended. For more information, review the AdMob policies and learn more about invalid activity.
How do I get test ads?
The ad unit and samples that we provide return test ads. You can also request test ads by using AdRequest.Builder.addTestDevice().
How do I get an AdMob ad unit ID?
Follow the directions for creating an ad unit. AdMob ad unit IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX/NNNNNNNNNN.

Send feedback about...

Need help? Visit our support page.