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.
- Running
Android Studio 1.0 or higher
- Developing
for Android API level 14 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:10.2.0'
}
...
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:
2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:tools="http://schemas.android.com/tools"
4. xmlns:ads="http://schemas.android.com/apk/res-auto"
5. android:layout_height="match_parent"
6. android:layout_width="match_parent"
7. android:paddingLeft="@dimen/activity_horizontal_margin"
8. android:paddingRight="@dimen/activity_horizontal_margin"
9. android:paddingTop="@dimen/activity_vertical_margin"
10. android:paddingBottom="@dimen/activity_vertical_margin"
11. tools:context=".MainActivity">
12.
13. <TextView
android:text="@string/hello_world"
14.
android:layout_width="wrap_content"
15.
android:layout_height="wrap_content" />
16.
17. <com.google.android.gms.ads.AdView
18.
android:id="@+id/adView"
19.
android:layout_width="wrap_content"
20.
android:layout_height="wrap_content"
21.
android:layout_centerHorizontal="true"
22.
android:layout_alignParentBottom="true"
23.
ads:adSize="BANNER"
24.
ads:adUnitId="@string/banner_ad_unit_id">
25. </com.google.android.gms.ads.AdView>
26.
</RelativeLayout>
- Add an
additional namespace to be used for ads:
28. http://schemas.android.com/apk/res-auto
- Add a
new element for your AdView.
- Set layout_width and layout_height to wrap_content.
- 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.
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 and AdView classes.
- 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
What’s next
To do more
with AdMob, sign up for an AdMob account.
To see how
to get Firebase and AdMob working together, check out the video to the right.
To fine-tune
your banner implementation, check out the following guides:
To learn
about full-screen interstitial ads, check out Interstitial Ads.
FAQ
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 320×50 test banner. Try
removing the android:paddingRight and android:paddingLeftattributes
from the RelativeLayout in activity_main.xml, and then recompiling
the app.
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.
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.
The ad unit and samples that we
provide return test ads. You can also request test ads by using AdRequest.Builder.addTestDevice().
Follow the directions for creating
an ad unit. AdMob ad unit IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX/NNNNNNNNNN.
Android Studio
Next Tutorial