Banner ads  |  Android  |  Google for Developers (2024)

Banner ads | Android | Google for Developers (1)

Banner ads are rectangular ads that occupy a portion of an app's layout. Theystay on screen while users are interacting with the app, either anchored at thetop or bottom of the screen or inline with content as the user scrolls. Bannerads can refresh automatically after a certain period of time. See Overview of banner adsfor more information.

This guide shows you how to get started with anchored adaptive bannerads,which maximizes performance by optimizing the ad size for each device usingan ad width you specify.

Anchored adaptive banner ads are fixed aspect ratio ads rather than the regularfixed size ads. The aspect ratio is similar to 320x50 industry standard. Onceyou specify the full width available, it will return you an ad with optimalheight for that width. The optimal height doesn't change across requests fromthe same device, and the surrounding views don't need to move when the adrefreshes.

Prerequisites

  • Complete the Get started guide.

Always test with test ads

When building and testing your apps, make sure you use test ads rather thanlive, production ads. Failure to do so can lead to suspension of your account.

The easiest way to load test ads is to use our dedicated test ad unit ID forAndroid banners:

ca-app-pub-3940256099942544/9214589741

It's been specially configured to return test ads for every request, and you canuse it in your own apps while coding, testing, and debugging. Just make sure youreplace it with your own ad unit ID before publishing your app.

For more information about how the Mobile Ads SDK's test ads work, see TestAds.

Add AdView to the layout

The first step toward displaying a banner is to place AdViewin the layout for the Activity or Fragment in which you'd like to display it.:

Java

private AdSize getAdSize() { // Determine the screen width (less decorations) to use for the ad width. Display display = getWindowManager().getDefaultDisplay(); DisplayMetrics outMetrics = new DisplayMetrics(); display.getMetrics(outMetrics); float density = outMetrics.density; float adWidthPixels = adContainerView.getWidth(); // If the ad hasn't been laid out, default to the full screen width. if (adWidthPixels == 0) { adWidthPixels = outMetrics.widthPixels; } int adWidth = (int) (adWidthPixels / density); return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth);}private void loadBanner() {  // Create a new ad view. AdView adView = new AdView(this); adView.setAdSizes(getAdSize()); adView.setAdUnitId("ca-app-pub-3940256099942544/9214589741"); // Replace ad container with new ad view. adContainerView.removeAllViews(); adContainerView.addView(adView); // Start loading the ad in the background. AdRequest adRequest = new AdRequest.Builder().build(); adView.loadAd(adRequest);}

Kotlin

// Determine the screen width (less decorations) to use for the ad width.// If the ad hasn't been laid out, default to the full screen width.private val adSize: AdSize get() { val display = windowManager.defaultDisplay val outMetrics = DisplayMetrics() display.getMetrics(outMetrics) val density = outMetrics.density var adWidthPixels = binding.adViewContainer.width.toFloat() if (adWidthPixels == 0f) { adWidthPixels = outMetrics.widthPixels.toFloat() } val adWidth = (adWidthPixels / density).toInt() return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth) }private fun loadBanner() {  // Create a new ad view. val adView = AdView(this) adView.adSizes = adSize adView.adUnitId = "ca-app-pub-3940256099942544/9214589741" // Create an ad request. val adRequest = AdRequest.Builder().build() // Start loading the ad in the background. adView.loadAd(adRequest)}

Load an ad

Once the AdView is in place, the next step is toload an ad. That's done with the loadAd()method in the AdView class. It takes an AdRequestparameter, which holds runtime information, such as targeting info, about asingle ad request.

Here's an example that shows how to load an ad in the onCreate() method of anActivity:

Java

private void loadBanner() { // Create a new ad view. adView = new AdView(this); adView.setAdUnitId(AD_UNIT); adView.setAdSize(getAdSize());  // Replace ad container with new ad view. adContainerView.removeAllViews(); adContainerView.addView(adView); // Start loading the ad in the background. AdRequest adRequest = new AdRequest.Builder().build(); adView.loadAd(adRequest);}

Kotlin

private fun loadBanner() { // This is an ad unit ID for a test ad. Replace with your own banner ad unit ID. adView.adUnitId = "/6499/example/banner" adView.setAdSize(adSize)  // Create an ad request. val adRequest = AdRequest.Builder().build() // Start loading the ad in the background. adView.loadAd(adRequest)}

If your ad fails to load, you don't need to explicitly request another one aslong as you've configured your ad unit to refresh; the Google Mobile Ads SDKrespects any refresh rate you specified in the AdMobweb interface. If you haven't enabled refresh, you will need to issue a newrequest.

That's it! Your app is now ready to display banner ads.

Ad events

To further customize the behavior of your ad, you can hook onto a number ofevents in the ad's lifecycle: loading, opening, closing, and so on. You canlisten for these events through theAdListener class.

To use anAdListener withAdView, call thesetAdListener()method:

Java

AdView.setAdListener(new AdListener() { @Override public void onAdClicked() { // Code to be executed when the user clicks on an ad. } @Override public void onAdClosed() { // Code to be executed when the user is about to return // to the app after tapping on an ad. } @Override public void onAdFailedToLoad(LoadAdError adError) { // Code to be executed when an ad request fails. } @Override public void onAdImpression() { // Code to be executed when an impression is recorded // for an ad. } @Override public void onAdLoaded() { // Code to be executed when an ad finishes loading. } @Override public void onAdOpened() { // Code to be executed when an ad opens an overlay that // covers the screen. }});

Kotlin

AdView.adListener = object: AdListener() { override fun onAdClicked() { // Code to be executed when the user clicks on an ad. } override fun onAdClosed() { // Code to be executed when the user is about to return // to the app after tapping on an ad. } override fun onAdFailedToLoad(adError : LoadAdError) { // Code to be executed when an ad request fails. } override fun onAdImpression() { // Code to be executed when an impression is recorded // for an ad. } override fun onAdLoaded() { // Code to be executed when an ad finishes loading. } override fun onAdOpened() { // Code to be executed when an ad opens an overlay that // covers the screen. }}

Each of the overridable methods inAdListenercorresponds to an event in the lifecycle of an ad.

Overridable methods
onAdClicked() The onAdClicked() method is invoked when a click is recorded for an ad.
onAdClosed() The onAdClosed() method is invoked when a user returns to the app after viewing an ad's destination URL. Your app can use it to resume suspended activities or perform any other work necessary to make itself ready for interaction. Refer to the AdMob AdListener example for an implementation of the ad listener methods in the Android API Demo app.
onAdFailedToLoad() The onAdFailedToLoad() method is the only one that includes a parameter. The error parameter of type LoadAdError describes what error occurred. For more information, refer to the Debugging Ad Load Errors documentation.
onAdImpression() The onAdImpression() method is invoked when an impression is recorded for an ad.
onAdLoaded() The onAdLoaded() method is executed when an ad has finished loading. If you want to delay adding the AdView to your activity or fragment until you're sure an ad will be loaded, for example, you can do so here.
onAdOpened() The onAdOpened() method is invoked when an ad opens an overlay that covers the screen.

Hardware acceleration for video ads

In order for video ads to show successfully in your banner ad views, hardwareacceleration mustbe enabled.

Hardware acceleration is enabled by default, but some apps may choose to disableit. If this applies to your app, we recommend enabling hardware acceleration forActivity classes that use ads.

Enabling hardware acceleration

If your app does not behave properly with hardware acceleration turned onglobally, you can control it for individual activities as well. To enable ordisable hardware acceleration, you can use the android:hardwareAcceleratedattribute for the<application>and<activity>elements in your AndroidManifest.xml. The following example enables hardwareacceleration for the entire app but disables it for one activity:

<application android:hardwareAccelerated="true"> <!-- For activities that use ads, hardwareAcceleration should be true. --> <activity android:hardwareAccelerated="true" /> <!-- For activities that don't use ads, hardwareAcceleration can be false. --> <activity android:hardwareAccelerated="false" /></application>

See the Hardware accelerationguide for moreinformation about options for controlling hardware acceleration. Note thatindividual ad views cannot be enabled for hardware acceleration if the activityis disabled, so the activity itself must have hardware acceleration enabled.

Additional resources

Examples on GitHub

Next steps

Collapsible banners

Collapsible banner ads are banner ads that are initially presented as a largeroverlay, with a button to collapse the ad to a smaller size. Consider using itto further optimize your performance. See collapsible banner ads for more details.

Inline adaptive banners

Inline adaptive banners are larger, taller banners compared to anchored adaptivebanners. They are of variable height, and can be as tall as the device screen.Inline adaptive banners are recommended over anchored adaptive banner ads forapps that place banner ads in scrollable content. See inline adaptivebanners for moredetails.

Explore other topics

  • User privacy
  • Optimize SDK initialization and ad loading(beta)
Banner ads  |  Android  |  Google for Developers (2024)
Top Articles
Latest Posts
Article information

Author: Roderick King

Last Updated:

Views: 5432

Rating: 4 / 5 (71 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Roderick King

Birthday: 1997-10-09

Address: 3782 Madge Knoll, East Dudley, MA 63913

Phone: +2521695290067

Job: Customer Sales Coordinator

Hobby: Gunsmithing, Embroidery, Parkour, Kitesurfing, Rock climbing, Sand art, Beekeeping

Introduction: My name is Roderick King, I am a cute, splendid, excited, perfect, gentle, funny, vivacious person who loves writing and wants to share my knowledge and understanding with you.