1. Introduction
Last Updated: 2020-01-10
Adaptive banners are the next generation of responsive ads, maximizing performance by optimizing ad size for each device. Improving on smart banners, which only supported fixed heights, adaptive banners let developers specify the ad width and use this to determine the optimal ad size.
AdMob supports Adaptive Banners by providing the Adaptive Banner API—a new way to request banner ads, and it only requires minimal changes from the existing banner ads API. In this new API, publishers requesting an Adaptive Banner ad specify the maximum available width for ads in the given placement, and pass this width to the banner ad request. AdMob then chooses the optimal banner creative for the device requesting the ad and the space available, aiming to maximize revenue performance and fill the available space.
This codelab will walk you through integrating an Adaptive Anchor banner to a new application. You'll start with an empty app created by Android Studio with no ads. Over the course of the codelab, you'll install the AdMob SDK, prepare your layout, and add code to load and display an Adaptive Anchor banner.
What you'll build
In this CodeLab, you're going to create a new blank application and then implement an Adaptive Anchor banner in the Java language
What you'll learn
- How to install the AdMob SDK in your application.
- How to integrate an Adaptive Anchor Banner with your application.
- How to set up your banner with a background.
What you'll need
- A recent version of Android Studio (3.5+)
- An Android Emulator running AVD (Android Virtual Device) with a system image that supports Play Store/Google APIs or a physical Android device.
2. Set up your Development Environment
Create a new Android Studio project
- Create a new project in Android Studio.
- Choose the Empty Activity template.
- Choose a minSDK version of 16 and the language as Java.
Add the Mobile Ads SDK to your project gradle file
- In your project-level
build.gradle
file, add the line:implementation 'com.google.android.gms:play-services-ads:18.3.0'
- Sync your project when prompted.
//add this line to install AdMob SDK:
implementation 'com.google.android.gms:play-services-ads:18.3.0'
3. Set up your AdMob Banner App ID
Update your AndroidManifest.xml
Add your AdMob App ID to your app's AndroidManifest.xml
file by adding the <meta-data>
tag. You can find your App ID in the AdMob UI. Insert your AdMob App ID in android:value
as shown below.
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--Add the app ID by using the <meta-data> tag -->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-3940256099942544~3347511713"/>
</application>
For the purpose of this codelab, you can use the sample App ID shown above. In a production app, you would Set up an app in AdMob and find your app ID in the AdMob UI.
Import the MobileAds package
To be able to use the MobileAds API, you need to import its package.
Add the following line into your MainActivity.java
file:
import com.google.android.gms.ads.MobileAds;
Initialize the Mobile Ads SDK
In order to use the Mobile Ads SDK, you need to initialize it. This needs to be done only once, ideally at app launch.
- In your
MainActivity.java
'sonCreate()
method, callMobileAds.initialize()
which initializes the SDK and calls back a completion listener once initialization is complete (or after a 30-second timeout).
If you're using mediation, wait until the completion handler is called before loading ads, as this will ensure that all mediation adapters are initialized. 2. When prompted by Android Studio, import the packages needed by the initialize()
function.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Call the function to initialize AdMob SDK
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
}
4. Create an AdView object and set your ad unit id
Unlike the NORMAL or SMART banners, where you can predefine the ad size, Adaptive Anchor Banner has a flexible, dynamic size that depends on the size of the device screen. Because of that, you will not be able to precreate your AdView
in layout, but need to do it in your code.
Even if you cannot precreate your AdView
in layout, but still want to define your banner position, you can create a placeholder where you will put the banner in later. In this codelab, you will create a placeholder for the Adaptive Banner at the bottom of the screen.
There are many different types of layout you can use as a placeholder. In this codelab, you use a FrameLayout
.
Create a FrameLayout
in your activity_main.xml
as shown below:
<FrameLayout
android:id="@+id/adView_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Create an AdView
- In your
MainActivity.java
define two variables: one for theFrameLayout
and one for theAdView
. - Then in your
MainActivity.java
'sonCreate()
function, create a newAdView
, set your ad unit ID, and add put it into yourFrameLayout
. - When prompted by Android Studio, import the packages needed by the
AdView and FrameLayout
functions.
private FrameLayout adContainerView;
private AdView adView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Call the function to initialize AdMob SDK
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
//get the reference to your FrameLayout
adContainerView = findViewById(R.id.adView_container);
//Create an AdView and put it into your FrameLayout
adView = new AdView(this);
adContainerView.addView(adView);
}
Set your Ad unit id
Set your AdMob Ad Unit ID to your AdView
by using the setAdUnitId()
API. Again, for this example, you can use AdMob's test ad unit:
//Create an AdView and put it into your FrameLayout
adView = new AdView(this);
adContainerView.addView(adView);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
5. Get the adaptive size and load your banner
There are three methods to get the ad size for an Adaptive Banner—one for landscape, one for portrait, and one for the current orientation at the time of execution. You provide your preferred width, and then the API will return the optimal size for the banner ad on the device running the app.
The Adaptive Banner sizes are designed to work best when using the full available width. In most cases, this will be the full width of the screen of the device in use. In this example, you will use the full width of the device for your banner.
Create a function to get the Adaptive Size
First, you need to define the width you want to use (in dp). Adaptive Banner APIs provide three APIs for you to get the optimal size depended on your orientation:
getLandscapeAnchoredAdaptiveBannerAdSize()
getPortraitAnchoredAdaptiveBannerAdSize()
getCurrentOrientationAnchoredAdaptiveBannerAdSize()
getCurrentOrientationAnchoredAdaptiveBannerAdSize()
is easy to use as it auto-detects the device's current orientation and returns the corresponding AdSize
. But if you want to preload in advance a banner in a specific orientation, then you can use the other APIs.
Try getCurrentOrientationAnchoredAdaptiveBannerAdSize()
:
private AdSize getAdSize() {
//Determine the screen width to use for the ad width.
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics();
display.getMetrics(outMetrics);
float widthPixels = outMetrics.widthPixels;
float density = outMetrics.density;
//you can also pass your selected width here in dp
int adWidth = (int) (widthPixels / density);
//return the optimal size depends on your orientation (landscape or portrait)
return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth);
}
Create a function to request your banner ads
Now, you are finally ready to load and show off your banner...
After having the size, you can create the function loadBanner()
in your MainActivity.java
to request your banner by calling the LoadAds()
function of the AdView
library:
private void loadBanner() {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.build();
AdSize adSize = getAdSize();
// Set the adaptive ad size to the ad view.
adView.setAdSize(adSize);
// Start loading the ad in the background.
adView.loadAd(adRequest);
}
Start requesting your Adaptive banner
Now in the onCreate()
function of your MainActivity.java
, after creating your BannerView and setting an ad unit to it, you can request a banner with adaptive size. Your banner will be shown automatically after an ad is returned.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Call the function to initialize AdMob SDK
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
//get the reference to your FrameLayout
adContainerView = findViewById(R.id.adView_container);
//Create an AdView and put it into your FrameLayout
adView = new AdView(this);
adContainerView.addView(adView);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
//start requesting banner ads
loadBanner();
}
Build and run your app to see the banner:
6. Create a background for your banner
Handling the overlapping with app content issue
Even if you use the full device screen width for your banner, there is still a chance that the returned creative (the actual ad) has a smaller size than your provided size. In this case AdMobSDK will try to scale the creative to fit the size while maintaining its ratio. This may create blank spaces as shown in the following screenshot:
This can create an ‘overlapping with app content' issue, where the ad obscures content from the user. To avoid that, you need to create a background that covers the whole banner size to make sure there will be no app content in the banner area.
Create a background
You can use the AdSize returned by AdMob API to create a background for your banner. As in the example, you already have the FrameLayout
as the container for the banner. You can set the background color for the FrameLayout
(which is transparent by default) in your activity_main.xml
file.
<FrameLayout
android:id="@+id/adView_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:background="#666666">
</FrameLayout>
Your result will look like this:
7. Congratulations
Congratulations, your app now is ready to display Adaptive Anchor Banner!
What we've covered
- How to install the Google Mobile Ads SDK.
- How to create and display banners with Adaptive Size.
- How to create a background to cover the whole banner size.
Next steps
- Sign up for an AdMob account.
- Create a banner ad unit.
- Use Adaptive Banner in your own app with your own ad unit.
Learn more
- Read the Adaptive Banner guide for more details.