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 Firebase and the Mobile Ads SDK
For more detail on how Firebase and AdMob work together and how this impacts existing AdMob publishers, see AdMob with Firebase.
To get started, see the Add Firebase to Your Android Project guide.
If you already have an AdMob account, you can register and link your app with Firebase from within the AdMob console.
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.firebase:firebase-ads:9.6.1'
}
...
apply plugin: 'com.google.gms.google-services'
If the two lines in bold above are not already in your app-level
build.gradle
, add them. Place the compile
statement inside the
dependencies
section and the apply plugin
statement at the bottom.
-
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.
-
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.
-
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 Firebase and 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
:
-
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>
-
Add an additional namespace to be used for ads:
http://schemas.android.com/apk/res-auto
-
Add a new element for your
AdView
. -
Set
layout_width
andlayout_height
towrap_content
. -
In the
AdView
tag, set theadSize
toBANNER
and theadUnitId
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.
Open your MainActivity.java file. It's in the BannerExample/app/src/main/java/
folder, though the exact subdirectory path varies based on the domain you used when creating
your project above. Once it's open in the editor, look for the onCreate()
method
in the MainActivity
class:
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.
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:
-
Import the
AdRequest
andAdView
classes. -
Find your
AdView
in the layout, create anAdRequest
, and then load an ad into theAdView
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
What's next
To do more with AdMob, sign up for an AdMob account.
To learn about full-screen interstitial ads, check out the Interstitial Ads guide.
To fine-tune your banner implementation, check out the following guides:
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
andandroid:paddingLeft
attributes from theRelativeLayout
in activity_main.xml, and then recompiling the app. - I see
onPause()
,onResume()
, andonDestroy()
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
.