### Complete Banner Implementation Example Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/03-banner-ads-api.md A full example demonstrating how to set up and load a banner ad within an Android Activity, including ad listener setup and lifecycle management. ```APIDOC ## Complete Banner Implementation Example ```java public class BannerActivity extends AppCompatActivity { private AdView adView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_banner); adView = findViewById(R.id.adView); // Set listener adView.setAdListener(new AdListener() { @Override public void onAdLoaded() { Log.d("Banner", "Ad loaded"); } @Override public void onAdFailedToLoad(LoadAdError adError) { Log.e("Banner", "Load error: " + adError.getMessage()); } }); // Load ad AdRequest request = new AdRequest.Builder().build(); adView.loadAd(request); } @Override protected void onDestroy() { if (adView != null) { adView.destroy(); } super.onDestroy(); } } ``` ``` -------------------------------- ### Complete Initialization Example Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/07-sdk-initialization-configuration.md An example demonstrating how to complete SDK initialization, including setting request configurations and handling the initialization callback. ```APIDOC ## Complete Initialization Example ### Description This example shows how to initialize the Google Mobile Ads SDK on a background thread. It includes configuring request settings like test device IDs, maximum ad content rating, child-directed treatment, and age-restricted treatment before initializing the SDK. A callback is provided to log the status of each adapter upon successful initialization. ### Method `MobileAds.initialize(Context, OnInitializationCompleteListener)` ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize SDK on background thread new Thread(() -> { // Configure request settings RequestConfiguration config = new RequestConfiguration.Builder() .setTestDeviceIds(Arrays.asList("33BE2250B43518CCDA7DE426D04EE231")) .setMaxAdContentRating(RequestConfiguration.MAX_AD_CONTENT_RATING_G) .setTagForChildDirectedTreatment( RequestConfiguration.TAG_FOR_CHILD_DIRECTED_TREATMENT_FALSE) .setAgeRestrictedTreatment(AgeRestrictedTreatment.UNSPECIFIED) .build(); // Set global configuration MobileAds.setRequestConfiguration(config); // Initialize SDK with callback MobileAds.initialize(this, status -> { // Log adapter status Map adapterStatus = status.getAdapterStatusMap(); for (Map.Entry entry : adapterStatus.entrySet()) { String adapterClass = entry.getKey(); AdapterStatus adapterStat = entry.getValue(); Log.d("MobileAds", String.format( "Adapter %s: %s (latency: %dms)", adapterClass, adapterStat.getDescription(), adapterStat.getLatency())); } Log.d("MobileAds", "SDK initialized"); }); }).start(); } } ``` ### Response #### Success Response (void) Initialization status is provided via the `OnInitializationCompleteListener` callback. #### Response Example None ``` -------------------------------- ### Ad Manager App Open Example (Java) Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/README.md Example implementation for App Open ads using Ad Manager in Java. Ensure proper setup and ad unit configuration. -------------------------------- ### AdMob App Open Example (Java) Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/README.md Provides an example for implementing App Open ads with AdMob in Java. ```Java This repository contains open source examples and developer resources for both the Google AdMob and Google Ad Manager components of the Google Mobile Ads SDK. # Google Mobile Ads SDK Developers forum To report SDK feature requests, bugs, and crashes or to browse SDK-related discussions, please use our [Google Mobile Ads SDK Developers forum](https://groups.google.com/forum/#!forum/google-admob-ads-sdk). The forum provides the latest SDK announcements and updates as well as technical SDK support for our [Android developers](https://groups.google.com/forum/#!categories/google-admob-ads-sdk/android). # Documentation Check out our [developers site](https://developers.google.com/admob/) for documentation on using the Mobile Ads SDK. # Examples ## AdMob * App Open: [Java](https://github.com/googleads/googleads-mobile-android-examples/tree/main/java/admob/AppOpenExample), [Kotlin](https://github.com/googleads/googleads-mobile-android-examples/tree/main/kotlin/admob/AppOpenExample) * Banner: [Java](https://github.com/googleads/googleads-mobile-android-examples/tree/main/java/admob/BannerExample), [Kotlin](https://github.com/googleads/googleads-mobile-android-examples/tree/main/kotlin/admob/BannerExample) * Interstitial: [Java](https://github.com/googleads/googleads-mobile-android-examples/tree/main/java/admob/InterstitialExample), [Kotlin](https://github.com/googleads/googleads-mobile-android-examples/tree/main/kotlin/admob/InterstitialExample) * Rewarded Interstitial: [Java](https://github.com/googleads/googleads-mobile-android-examples/tree/main/java/admob/RewardedInterstitialExample), [Kotlin](https://github.com/googleads/googleads-mobile-android-examples/tree/main/kotlin/admob/RewardedInterstitialExample) * Rewarded Video: [Java](https://github.com/googleads/googleads-mobile-android-examples/tree/main/java/admob/RewardedVideoExample), [Kotlin](https://github.com/googleads/googleads-mobile-android-examples/tree/main/kotlin/admob/RewardedVideoExample) * Native Advanced: [Java](https://github.com/googleads/googleads-mobile-android-examples/tree/main/java/admob/NativeAdvancedExample), [Kotlin](https://github.com/googleads/googleads-mobile-android-examples/tree/main/kotlin/admob/NativeAdvancedExample) ## Advanced * API Demo: [Java](https://github.com/googleads/googleads-mobile-android-examples/tree/main/java/advanced/APIDemo), [Kotlin](https://github.com/googleads/googleads-mobile-android-examples/tree/main/kotlin/advanced/APIDemo) - Provides additional examples for both AdMob and Ad Manager to help improve your mobile app integration of the Google Mobile Ads SDK. * Inline Adaptive Banner RecyclerView: [Java](https://github.com/googleads/googleads-mobile-android-examples/tree/main/java/advanced/InlineAdaptiveBannerExample) - Provides an example for displaying ads from AdMob inline adaptive banner ads in a RecyclerView widget. ``` -------------------------------- ### Complete Interstitial Ad Example Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/04-fullscreen-ads-api.md This example demonstrates loading, setting up callbacks, and showing an interstitial ad. It includes logic to load the next ad after the current one is dismissed. ```java public class InterstitialActivity extends AppCompatActivity { private InterstitialAd interstitialAd; private void loadInterstitial() { InterstitialAd.load(this, AD_UNIT_ID, new AdRequest.Builder().build(), new InterstitialAdLoadCallback() { @Override public void onAdLoaded(InterstitialAd ad) { interstitialAd = ad; setupInterstitialCallback(); } @Override public void onAdFailedToLoad(LoadAdError adError) { Log.e("Interstitial", adError.getMessage()); } }); } private void setupInterstitialCallback() { interstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() { @Override public void onAdShowedFullScreenContent() { Log.d("Interstitial", "Shown"); } @Override public void onAdDismissedFullScreenContent() { interstitialAd = null; // Load next ad loadInterstitial(); } @Override public void onAdFailedToShowFullScreenContent(AdError adError) { interstitialAd = null; } }); } public void showInterstitial() { if (interstitialAd != null) { interstitialAd.show(InterstitialActivity.this); } } } ``` -------------------------------- ### Complete Revenue Tracking Example Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/08-mediation-and-revenue.md Implement a paid event listener to capture and process ad revenue data. This example shows how to extract revenue details, ad source information, and send the data to an analytics service like Firebase Analytics. ```java public class RevenueTrackingActivity extends AppCompatActivity { private void setupRevenueTracking(RewardedAd ad) { ad.setOnPaidEventListener(adValue -> { // Extract revenue data long valueMicros = adValue.getValueMicros(); String currencyCode = adValue.getCurrencyCode(); int precision = adValue.getPrecisionType(); // Get ad source information ResponseInfo responseInfo = ad.getResponseInfo(); AdapterResponseInfo loadedAdapter = responseInfo.getLoadedAdapterResponseInfo(); String adSourceName = "Unknown"; String adSourceId = "Unknown"; if (loadedAdapter != null) { adSourceName = loadedAdapter.getAdSourceName(); adSourceId = loadedAdapter.getAdSourceId(); } // Create revenue event RevenueEvent event = new RevenueEvent( valueMicros, currencyCode, getPrecisionName(precision), adSourceName, adSourceId, ad.getAdUnitId() ); // Send to analytics service sendToAnalytics(event); }); } private String getPrecisionName(int precision) { switch (precision) { case AdValue.PRECISION_ESTIMATED: return "estimated"; case AdValue.PRECISION_PUBLISHER_PROVIDED: return "publisher_provided"; case AdValue.PRECISION_PRECISE: return "precise"; default: return "unknown"; } } private void sendToAnalytics(RevenueEvent event) { // Example: Firebase Analytics Bundle bundle = new Bundle(); bundle.putLong("value", event.valueMicros); bundle.putString("currency", event.currencyCode); bundle.putString("precision", event.precision); bundle.putString("ad_source", event.adSourceName); bundle.putString("ad_unit_id", event.adUnitId); FirebaseAnalytics.getInstance(this) .logEvent("ad_impression_revenue", bundle); } private static class RevenueEvent { long valueMicros; String currencyCode; String precision; String adSourceName; String adSourceId; String adUnitId; RevenueEvent(long valueMicros, String currencyCode, String precision, String adSourceName, String adSourceId, String adUnitId) { this.valueMicros = valueMicros; this.currencyCode = currencyCode; this.precision = precision; this.adSourceName = adSourceName; this.adSourceId = adSourceId; this.adUnitId = adUnitId; } } } ``` -------------------------------- ### Start Interstitial Ad Preloading (No Callback) Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/09-preloading-api.md Starts preloading interstitial ads without providing a callback for completion events. Use this when immediate feedback on preloading status is not required. ```java static void start(String adUnitId, PreloadConfiguration configuration) ``` ```java PreloadConfiguration config = new PreloadConfiguration.Builder(AD_UNIT_ID) .setBufferSize(3) .build(); InterstitialAdPreloader.start(AD_UNIT_ID, config); ``` -------------------------------- ### Interstitial Ad Example Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/04-fullscreen-ads-api.md Example of loading and showing an interstitial ad, including callback handling. ```APIDOC ## InterstitialAd Example ### Description This example demonstrates how to load and display an interstitial ad, and how to handle its lifecycle events. ### Loading an Interstitial Ad ```java private void loadInterstitial() { InterstitialAd.load(this, AD_UNIT_ID, new AdRequest.Builder().build(), new InterstitialAdLoadCallback() { @Override public void onAdLoaded(InterstitialAd ad) { interstitialAd = ad; setupInterstitialCallback(); } @Override public void onAdFailedToLoad(LoadAdError adError) { Log.e("Interstitial", adError.getMessage()); } }); } ``` ### Setting Up Callbacks ```java private void setupInterstitialCallback() { interstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() { @Override public void onAdShowedFullScreenContent() { Log.d("Interstitial", "Shown"); } @Override public void onAdDismissedFullScreenContent() { interstitialAd = null; // Load next ad loadInterstitial(); } @Override public void onAdFailedToShowFullScreenContent(AdError adError) { interstitialAd = null; } }); } ``` ### Showing an Interstitial Ad ```java public void showInterstitial() { if (interstitialAd != null) { interstitialAd.show(InterstitialActivity.this); } } ``` ``` -------------------------------- ### Start Interstitial Ad Preloading (With Callback) Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/09-preloading-api.md Starts preloading interstitial ads and provides event callbacks for preloading status. Implement PreloadCallbackV2 to handle preloaded ads, exhaustion, or failures. ```java static void start(String adUnitId, PreloadConfiguration configuration, PreloadCallbackV2 callback) ``` ```java PreloadConfiguration config = new PreloadConfiguration.Builder(AD_UNIT_ID) .setBufferSize(5) .build(); PreloadCallbackV2 callback = new PreloadCallbackV2() { @Override public void onAdPreloaded(String preloadId, ResponseInfo responseInfo) { Log.d("Preload", "Ad preloaded: " + preloadId); } @Override public void onAdsExhausted(String preloadId) { Log.d("Preload", "No more ads available: " + preloadId); } @Override public void onAdFailedToPreload(String preloadId, AdError adError) { Log.d("Preload", "Failed to preload: " + adError.getMessage()); } }; InterstitialAdPreloader.start(AD_UNIT_ID, config, callback); ``` -------------------------------- ### Complete Preloading Example Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/09-preloading-api.md Demonstrates how to set up and manage preloaded interstitial ads. This includes defining configurations, handling callbacks, and showing preloaded ads. ```java public class PreloadingActivity extends AppCompatActivity { private static final String INTERSTITIAL_AD_UNIT = "ca-app-pub-3940256099942544/1033173712"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Start preloading on app launch startPreloading(); } private void startPreloading() { // Define configuration PreloadConfiguration config = new PreloadConfiguration.Builder(INTERSTITIAL_AD_UNIT) .setBufferSize(3) // Keep 3 ads ready .build(); // Define callbacks PreloadCallbackV2 callback = new PreloadCallbackV2() { @Override public void onAdPreloaded(String preloadId, ResponseInfo responseInfo) { Log.d("Preload", "Ad preloaded. Available: " + InterstitialAdPreloader.getNumAdsAvailable(INTERSTITIAL_AD_UNIT)); } @Override public void onAdsExhausted(String preloadId) { Log.d("Preload", "All ads exhausted - buffer empty"); } @Override public void onAdFailedToPreload(String preloadId, AdError adError) { Log.e("Preload", "Failed to preload: " + adError.getMessage()); } }; // Start preloading InterstitialAdPreloader.start(INTERSTITIAL_AD_UNIT, config, callback); } public void showInterstitial() { // Check if ad is available if (InterstitialAdPreloader.isAdAvailable(INTERSTITIAL_AD_UNIT)) { // Poll (get and remove from buffer) InterstitialAd ad = InterstitialAdPreloader.pollAd(INTERSTITIAL_AD_UNIT); if (ad != null) { // Optional: Set up listeners ad.setOnPaidEventListener(adValue -> { long revenue = adValue.getValueMicros(); String currency = adValue.getCurrencyCode(); // Log revenue Log.d("Revenue", revenue + " " + currency); }); // Show the ad ad.show(PreloadingActivity.this); } } else { Log.d("Preload", "No ads available to show"); // Optionally, load an ad on-demand while waiting for preload } } @Override protected void onDestroy() { // Clean up all preloaded ads InterstitialAdPreloader.destroyAll(); super.onDestroy(); } } ``` -------------------------------- ### Run Gradle Project Locally Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/java/advanced/RewardedSSVExample/README.md Navigate to the project directory and run the Gradle wrapper to start the Spring-Boot application locally. ```bash cd RewardedSSVExample ./gradlew bootRun ``` -------------------------------- ### Get SDK Version String Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/07-sdk-initialization-configuration.md Retrieves the current version string of the Google Mobile Ads SDK. Example format: "25.4.0". ```java static String getVersionString() ``` -------------------------------- ### Complete Type Usage Example Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/10-types-and-enums.md Demonstrates the usage of various types and constants including AdSize, NativeAdOptions, RequestConfiguration, and AdValue precision types. ```APIDOC ## Complete Type Usage Example ```java public class TypeExampleActivity extends AppCompatActivity { private void demonstrateTypes() { // AdSize example AdSize bannerSize = AdSize.BANNER; // 320x50 dp AdSize rectangleSize = AdSize.MEDIUM_RECTANGLE; // 300x250 dp // Adaptive size AdSize adaptiveSize = AdSize.getInlineAdaptiveBannerAdSize( getResources().getDisplayMetrics().widthPixels ); // MediaAspectRatio example NativeAdOptions options = new NativeAdOptions.Builder() .setMediaAspectRatio(MediaAspectRatio.LANDSCAPE) .setAdChoicesPlacement(NativeAdOptions.ADCHOICES_BOTTOM_RIGHT) .build(); // RequestConfiguration with constants RequestConfiguration config = new RequestConfiguration.Builder() .setMaxAdContentRating(RequestConfiguration.MAX_AD_CONTENT_RATING_PG) .setTagForChildDirectedTreatment( RequestConfiguration.TAG_FOR_CHILD_DIRECTED_TREATMENT_FALSE) .setTagForUnderAgeOfConsent( RequestConfiguration.TAG_FOR_UNDER_AGE_OF_CONSENT_FALSE) .build(); // AdValue precision types OnPaidEventListener listener = adValue -> { int precision = adValue.getPrecisionType(); String label; switch (precision) { case AdValue.PRECISION_ESTIMATED: label = "Estimated"; break; case AdValue.PRECISION_PUBLISHER_PROVIDED: label = "Publisher Provided"; break; case AdValue.PRECISION_PRECISE: label = "Precise"; break; default: label = "Unknown"; } Log.d("AdValue", "Precision: " + label); }; } } ``` ``` -------------------------------- ### Initialize SDK with Callback Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/07-sdk-initialization-configuration.md This example demonstrates how to initialize the Mobile Ads SDK on a background thread and set global request configurations. It includes a callback to log the status of adapter initialization. ```java public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize SDK on background thread new Thread(() -> { // Configure request settings RequestConfiguration config = new RequestConfiguration.Builder() .setTestDeviceIds(Arrays.asList("33BE2250B43518CCDA7DE426D04EE231")) .setMaxAdContentRating(RequestConfiguration.MAX_AD_CONTENT_RATING_G) .setTagForChildDirectedTreatment( RequestConfiguration.TAG_FOR_CHILD_DIRECTED_TREATMENT_FALSE) .setAgeRestrictedTreatment(AgeRestrictedTreatment.UNSPECIFIED) .build(); // Set global configuration MobileAds.setRequestConfiguration(config); // Initialize SDK with callback MobileAds.initialize(this, status -> { // Log adapter status Map adapterStatus = status.getAdapterStatusMap(); for (Map.Entry entry : adapterStatus.entrySet()) { String adapterClass = entry.getKey(); AdapterStatus adapterStat = entry.getValue(); Log.d("MobileAds", String.format( "Adapter %s: %s (latency: %dms)", adapterClass, adapterStat.getDescription(), adapterStat.getLatency())); } Log.d("MobileAds", "SDK initialized"); }); }).start(); } } ``` -------------------------------- ### Complete Type Usage Example Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/10-types-and-enums.md Demonstrates the usage of various types and enums including `AdSize`, `NativeAdOptions`, `RequestConfiguration`, and `AdValue` precision. ```java public class TypeExampleActivity extends AppCompatActivity { private void demonstrateTypes() { // AdSize example AdSize bannerSize = AdSize.BANNER; // 320x50 dp AdSize rectangleSize = AdSize.MEDIUM_RECTANGLE; // 300x250 dp // Adaptive size AdSize adaptiveSize = AdSize.getInlineAdaptiveBannerAdSize( getResources().getDisplayMetrics().widthPixels ); // MediaAspectRatio example NativeAdOptions options = new NativeAdOptions.Builder() .setMediaAspectRatio(MediaAspectRatio.LANDSCAPE) .setAdChoicesPlacement(NativeAdOptions.ADCHOICES_BOTTOM_RIGHT) .build(); // RequestConfiguration with constants RequestConfiguration config = new RequestConfiguration.Builder() .setMaxAdContentRating(RequestConfiguration.MAX_AD_CONTENT_RATING_PG) .setTagForChildDirectedTreatment( RequestConfiguration.TAG_FOR_CHILD_DIRECTED_TREATMENT_FALSE) .setTagForUnderAgeOfConsent( RequestConfiguration.TAG_FOR_UNDER_AGE_OF_CONSENT_FALSE) .build(); // AdValue precision types OnPaidEventListener listener = adValue -> { int precision = adValue.getPrecisionType(); String label; switch (precision) { case AdValue.PRECISION_ESTIMATED: label = "Estimated"; break; case AdValue.PRECISION_PUBLISHER_PROVIDED: label = "Publisher Provided"; break; case AdValue.PRECISION_PRECISE: label = "Precise"; break; default: label = "Unknown"; } Log.d("AdValue", "Precision: " + label); }; } } ``` -------------------------------- ### Initialize AdRequest.Builder Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/02-ad-request-api.md Standard constructor for AdRequest.Builder. Use this to start building an ad request. ```java AdRequest.Builder() ``` -------------------------------- ### Get Response Info Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/04-fullscreen-ads-api.md Returns response metadata for the loaded ad. ```java ResponseInfo getResponseInfo() ``` -------------------------------- ### Complete Banner Ad Implementation Example Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/03-banner-ads-api.md A full implementation of a banner ad within an Android Activity. Includes setting up the AdView, handling ad loading events, and managing the ad lifecycle. ```java public class BannerActivity extends AppCompatActivity { private AdView adView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_banner); adView = findViewById(R.id.adView); // Set listener adView.setAdListener(new AdListener() { @Override public void onAdLoaded() { Log.d("Banner", "Ad loaded"); } @Override public void onAdFailedToLoad(LoadAdError adError) { Log.e("Banner", "Load error: " + adError.getMessage()); } }); // Load ad AdRequest request = new AdRequest.Builder().build(); adView.loadAd(request); } @Override protected void onDestroy() { if (adView != null) { adView.destroy(); } super.onDestroy(); } } ``` -------------------------------- ### InterstitialAdPreloader.start(String, PreloadConfiguration, PreloadCallbackV2) Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/09-preloading-api.md Starts preloading with event callbacks. This method allows you to receive notifications about the preloading status, such as when an ad is preloaded, when ads are exhausted, or when preloading fails. ```APIDOC ## InterstitialAdPreloader.start(String, PreloadConfiguration, PreloadCallbackV2) ### Description Starts preloading with event callbacks. This method allows you to receive notifications about the preloading status, such as when an ad is preloaded, when ads are exhausted, or when preloading fails. ### Method static void ### Parameters #### Path Parameters - **adUnitId** (String) - Required - Ad unit ID - **configuration** (PreloadConfiguration) - Required - Preload configuration - **callback** (PreloadCallbackV2) - Required - Event callback ### Request Example ```java PreloadConfiguration config = new PreloadConfiguration.Builder(AD_UNIT_ID) .setBufferSize(5) .build(); PreloadCallbackV2 callback = new PreloadCallbackV2() { @Override public void onAdPreloaded(String preloadId, ResponseInfo responseInfo) { Log.d("Preload", "Ad preloaded: " + preloadId); } @Override public void onAdsExhausted(String preloadId) { Log.d("Preload", "No more ads available: " + preloadId); } @Override public void onAdFailedToPreload(String preloadId, AdError adError) { Log.e("Preload", "Failed to preload: " + adError.getMessage()); } }; InterstitialAdPreloader.start(AD_UNIT_ID, config, callback); ``` ``` -------------------------------- ### InterstitialAdPreloader.start(String, PreloadConfiguration) Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/09-preloading-api.md Starts preloading ads without a callback. This method initiates the ad preloading process for a given ad unit ID with specified preload configurations. ```APIDOC ## InterstitialAdPreloader.start(String, PreloadConfiguration) ### Description Starts preloading ads without a callback. This method initiates the ad preloading process for a given ad unit ID with specified preload configurations. ### Method static void ### Parameters #### Path Parameters - **adUnitId** (String) - Required - Interstitial ad unit ID - **configuration** (PreloadConfiguration) - Required - Preload configuration ### Request Example ```java PreloadConfiguration config = new PreloadConfiguration.Builder(AD_UNIT_ID) .setBufferSize(3) .build(); InterstitialAdPreloader.start(AD_UNIT_ID, config); ``` ``` -------------------------------- ### Test Server-Side Verification Endpoint Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/java/advanced/RewardedSSVExample/README.md Send a GET request to the local verification endpoint with data, signature, and key ID to test the callback verification. ```bash localhost:8080/verify?&signature=&key_id= ``` -------------------------------- ### VideoOptions Builder Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/10-types-and-enums.md Use the VideoOptions.Builder to configure video playback settings such as starting muted or requesting custom controls. Call build() to create the VideoOptions object. ```java new VideoOptions.Builder() .setStartMuted(boolean muted) .setCustomControlsRequested(boolean requested) .build() ``` -------------------------------- ### Fullscreen Ad Error Handling Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/06-response-info-and-errors.md Implement a FullScreenContentCallback to handle errors when showing a fullscreen ad. This example logs the error message and initiates loading a new ad. ```java interstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() { @Override public void onAdFailedToShowFullScreenContent(AdError adError) { Log.e("Interstitial", "Show failed: " + adError.getMessage()); interstitialAd = null; // Load new ad loadInterstitial(); } }); ``` -------------------------------- ### InterstitialAdPreloader.pollAd(String) Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/09-preloading-api.md Retrieves the next available preloaded ad and starts loading the next one in the background. Use this method to get a preloaded ad when you are ready to display it. ```APIDOC ## InterstitialAdPreloader.pollAd(String) ### Description Retrieves the next available preloaded ad and starts loading the next one in the background. Use this method to get a preloaded ad when you are ready to display it. ### Method static InterstitialAd ### Parameters #### Path Parameters - **adUnitId** (String) - Required - Ad unit ID ### Returns - **InterstitialAd** - next preloaded ad (null if none available) ### Request Example ```java InterstitialAd ad = InterstitialAdPreloader.pollAd(AD_UNIT_ID); if (ad != null) { ad.show(activity); } else { Log.d("Preload", "No ad available"); } ``` ``` -------------------------------- ### Get Loaded Adapter Response Info Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/06-response-info-and-errors.md Retrieve the response information for the adapter that successfully served the ad. Returns null if no ad was loaded. ```java AdapterResponseInfo loadedInfo = info.getLoadedAdapterResponseInfo(); if (loadedInfo != null) { Log.d("Ads", "Loaded from: " + loadedInfo.getAdSourceName()); } ``` -------------------------------- ### Configure Video Options for Native Ads Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/05-native-ads-api.md Set video playback behavior for native ads by providing a VideoOptions object. This allows customization of features like starting muted or requesting custom controls. ```java VideoOptions videoOptions = new VideoOptions.Builder() .setStartMuted(false) .setCustomControlsRequested(true) .build() NativeAdOptions nativeOptions = new NativeAdOptions.Builder() .setVideoOptions(videoOptions) .build() ``` -------------------------------- ### Set Video Start Muted Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/10-types-and-enums.md Configure whether video ads should automatically start with their sound muted. This method is part of the VideoOptions.Builder. ```java VideoOptions.Builder setStartMuted(boolean startMuted) ``` -------------------------------- ### Initialize SDK with Completion Listener Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/07-sdk-initialization-configuration.md Initializes the SDK and provides a callback to be notified upon completion. The callback allows checking the initialization status of mediation adapters. ```java new Thread(() -> { MobileAds.initialize(this, status -> { // Check adapter initialization status Map statusMap = status.getAdapterStatusMap(); for (String key : statusMap.keySet()) { AdapterStatus adapterStatus = statusMap.get(key); Log.d("MobileAds", key + ": " + adapterStatus.getDescription()); } }); }).start(); ``` -------------------------------- ### Run with Docker Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/java/advanced/RewardedSSVExample/README.md Use Docker Compose to build and run the application locally. ```bash docker-compose up --build ``` -------------------------------- ### Get Video Duration Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/05-native-ads-api.md Retrieve the total duration of the video in milliseconds. ```java int getDuration() ``` -------------------------------- ### InitializationStatus Methods Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/07-sdk-initialization-configuration.md Methods for retrieving initialization status information about the SDK and mediation adapters. ```APIDOC ## getAdapterStatusMap() ### Description Returns initialization status for all mediation adapters. ### Method ```java Map getAdapterStatusMap() ``` ### Returns Map - adapter class names to status ### Example ```java Map statusMap = initStatus.getAdapterStatusMap(); for (String adapterClass : statusMap.keySet()) { AdapterStatus status = statusMap.get(adapterClass); Log.d("Adapter", adapterClass + ": " + status.getDescription()); } ``` ``` -------------------------------- ### Core Initialization Methods Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/00-index.md These methods are essential for initializing the Mobile Ads SDK and setting up global configurations. ```APIDOC ## Core Initialization ### `MobileAds.initialize()` **Description**: Initializes the Mobile Ads SDK. This method should be called before any other Mobile Ads SDK methods. ### `MobileAds.setRequestConfiguration()` **Description**: Sets the global request configuration for the Mobile Ads SDK. This allows you to configure settings like child-directed treatment and tag for under 13 treatment. ### `MobileAds.openAdInspector()` **Description**: Opens the Ad Inspector, a tool that allows you to preview and debug ads in your app during development. ``` -------------------------------- ### Get Under Age of Consent Tag Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/07-sdk-initialization-configuration.md Retrieves the under-age-of-consent setting for ad requests. ```java int getTagForUnderAgeOfConsent() ``` -------------------------------- ### Get AdError Cause Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/06-response-info-and-errors.md Retrieve the underlying AdError cause from an AdError object. ```java AdError getCause() ``` -------------------------------- ### MobileAds.initialize(Context, OnInitializationCompleteListener) Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/07-sdk-initialization-configuration.md Initializes the SDK with a completion callback, allowing you to monitor the initialization status of mediation adapters. ```APIDOC ## initialize(Context, OnInitializationCompleteListener) ### Description Initializes the SDK with a completion callback. ### Method `static void` ### Parameters #### Path Parameters - **context** (Context) - Required - Application context - **listener** (OnInitializationCompleteListener) - Required - Callback with initialization status ### Request Example ```java new Thread(() -> { MobileAds.initialize(this, status -> { // Check adapter initialization status Map statusMap = status.getAdapterStatusMap(); for (String key : statusMap.keySet()) { AdapterStatus adapterStatus = statusMap.get(key); Log.d("MobileAds", key + ": " + adapterStatus.getDescription()); } }); }).start(); ``` ``` -------------------------------- ### Get AdError Message Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/06-response-info-and-errors.md Retrieve the error message string from an AdError object. ```java String getMessage() ``` -------------------------------- ### Initialize Mobile Ads SDK on App Startup Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/11-practical-examples.md Initialize the Mobile Ads SDK on application startup. Configure global request settings such as test device IDs, COPPA compliance, GDPR consent, and ad content rating. Initialization is performed on a background thread to avoid blocking the main thread. ```java public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); initializeMobileAds(); } private void initializeMobileAds() { // Initialize on background thread new Thread(() -> { // Configure global request settings RequestConfiguration config = new RequestConfiguration.Builder() // Test devices for development .setTestDeviceIds(Arrays.asList("33BE2250B43518CCDA7DE426D04EE231")) // Child-directed treatment for COPPA .setTagForChildDirectedTreatment( RequestConfiguration.TAG_FOR_CHILD_DIRECTED_TREATMENT_FALSE) // Under age of consent for GDPR .setTagForUnderAgeOfConsent( RequestConfiguration.TAG_FOR_UNDER_AGE_OF_CONSENT_FALSE) // Maximum ad content rating .setMaxAdContentRating(RequestConfiguration.MAX_AD_CONTENT_RATING_G) // Age restriction treatment .setAgeRestrictedTreatment(AgeRestrictedTreatment.UNSPECIFIED) .build(); // Apply global configuration MobileAds.setRequestConfiguration(config); // Initialize SDK MobileAds.initialize(this, status -> { // Log initialization status for debugging Map statusMap = status.getAdapterStatusMap(); for (String key : statusMap.keySet()) { AdapterStatus adapterStatus = statusMap.get(key); Log.d("MobileAds", String.format( "Adapter %s: %s (latency: %dms)", key, adapterStatus.getDescription(), adapterStatus.getLatency())); } Log.d("MobileAds", "SDK initialized successfully"); }); }).start(); } } ``` -------------------------------- ### Get AdError Domain Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/06-response-info-and-errors.md Retrieve the error domain string from an AdError object. ```java String getDomain() ``` -------------------------------- ### Display Interstitial Ad with Preloading (Java) Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/11-practical-examples.md Demonstrates how to preload and display interstitial ads efficiently. It maintains a buffer of ads to ensure a smooth user experience and logs ad revenue. ```java public class InterstitialPreloadActivity extends AppCompatActivity { private static final String INTERSTITIAL_AD_UNIT_ID = "ca-app-pub-3940256099942544/1033173712"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Start preloading on app launch startPreloading(); // Show ad on button click findViewById(R.id.showAdButton).setOnClickListener(v -> showInterstitial()); } private void startPreloading() { PreloadConfiguration config = new PreloadConfiguration.Builder(INTERSTITIAL_AD_UNIT_ID) .setBufferSize(2) // Maintain 2 ads in buffer .build(); PreloadCallbackV2 callback = new PreloadCallbackV2() { @Override public void onAdPreloaded(String preloadId, ResponseInfo responseInfo) { Log.d("Preload", "Ad preloaded, available: " + InterstitialAdPreloader.getNumAdsAvailable(INTERSTITIAL_AD_UNIT_ID)); } @Override public void onAdsExhausted(String preloadId) { Log.w("Preload", "No more ads in buffer"); } @Override public void onAdFailedToPreload(String preloadId, AdError adError) { Log.e("Preload", "Failed: " + adError.getMessage()); } }; InterstitialAdPreloader.start(INTERSTITIAL_AD_UNIT_ID, config, callback); } private void showInterstitial() { if (InterstitialAdPreloader.isAdAvailable(INTERSTITIAL_AD_UNIT_ID)) { InterstitialAd ad = InterstitialAdPreloader.pollAd(INTERSTITIAL_AD_UNIT_ID); if (ad != null) { // Set up callbacks ad.setFullScreenContentCallback(new FullScreenContentCallback() { @Override public void onAdShowedFullScreenContent() { Log.d("Interstitial", "Ad shown"); } @Override public void onAdDismissedFullScreenContent() { Log.d("Interstitial", "Ad dismissed"); } @Override public void onAdFailedToShowFullScreenContent(AdError adError) { Log.e("Interstitial", "Failed to show: " + adError.getMessage()); } }); // Track revenue ad.setOnPaidEventListener(adValue -> { logAdRevenue(adValue, ad.getAdUnitId()); }); // Show ad ad.show(InterstitialPreloadActivity.this); } } else { Log.d("Interstitial", "No ads available"); // Optionally load an ad on-demand } } private void logAdRevenue(AdValue adValue, String adUnitId) { long valueMicros = adValue.getValueMicros(); String currency = adValue.getCurrencyCode(); int precision = adValue.getPrecisionType(); String precisionName; switch (precision) { case AdValue.PRECISION_ESTIMATED: precisionName = "estimated"; break; case AdValue.PRECISION_PUBLISHER_PROVIDED: precisionName = "publisher_provided"; break; case AdValue.PRECISION_PRECISE: precisionName = "precise"; break; default: precisionName = "unknown"; } Log.d("Revenue", String.format( "Ad Revenue: %.4f %s (%s) from %s", valueMicros / 1_000_000.0, currency, precisionName, adUnitId)); // Send to analytics // analytics.logAdRevenue(valueMicros, currency, adUnitId); } @Override protected void onDestroy() { InterstitialAdPreloader.destroyAll(); super.onDestroy(); } } ``` -------------------------------- ### Get AdError Code Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/06-response-info-and-errors.md Retrieve the integer error code from an AdError object. ```java int getCode() ``` -------------------------------- ### Ad Inspector Error Handling Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/06-response-info-and-errors.md Example of handling errors when opening the ad inspector. ```APIDOC ### Ad Inspector Error Handling ```java MobileAds.openAdInspector(context, error -> { if (error != null) { Log.e("AdInspector", "Inspector error: " + error.getCode()); } else { Log.d("AdInspector", "Inspector closed without error"); } }); ``` ``` -------------------------------- ### SDK Initialization Complete Callback Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/07-sdk-initialization-configuration.md This method is called when the SDK has finished initializing. It provides an InitializationStatus object containing details about the initialized adapters. ```java void onInitializationComplete(InitializationStatus status) ``` -------------------------------- ### Get Age Restricted Treatment Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/07-sdk-initialization-configuration.md Retrieves the age restriction treatment setting for ads. ```java AgeRestrictedTreatment getAgeRestrictedTreatment() ``` -------------------------------- ### Get Publisher Privacy Personalization State Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/07-sdk-initialization-configuration.md Retrieves the publisher privacy personalization setting. ```java PublisherPrivacyPersonalizationState getPublisherPrivacyPersonalizationState() ``` -------------------------------- ### Load and Show Rewarded Ad with Server-Side Verification Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/11-practical-examples.md This snippet shows how to load a rewarded ad, set up server-side verification with custom data, handle ad display, and manage user rewards. It also includes callbacks for ad loading, dismissal, and errors, as well as a paid event listener for revenue tracking. Ensure the ad unit ID is valid and the SDK is initialized. ```java public class RewardedAdActivity extends AppCompatActivity { private static final String REWARDED_AD_UNIT_ID = "ca-app-pub-3940256099942544/5224354917"; private RewardedAd rewardedAd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.watchAdButton).setOnClickListener(v -> showRewardedAd()); } private void loadRewardedAd() { RewardedAd.load(this, REWARDED_AD_UNIT_ID, new AdRequest.Builder().build(), new RewardedAdLoadCallback() { @Override public void onAdLoaded(RewardedAd ad) { rewardedAd = ad; // Set up server-side verification String customData = generateCustomData(); ServerSideVerificationOptions options = new ServerSideVerificationOptions.Builder() .setCustomData(customData) .build(); rewardedAd.setServerSideVerificationOptions(options); // Set fullscreen callback rewardedAd.setFullScreenContentCallback( new FullScreenContentCallback() { @Override public void onAdDismissedFullScreenContent() { Log.d("Rewarded", "Ad dismissed"); rewardedAd = null; // Load next ad loadRewardedAd(); } @Override public void onAdFailedToShowFullScreenContent( AdError adError) { Log.e("Rewarded", "Show failed: " + adError.getMessage()); rewardedAd = null; } }); // Set revenue listener rewardedAd.setOnPaidEventListener(adValue -> { Log.d("Revenue", String.format( " Rewarded ad revenue: %.4f %s", adValue.getValueMicros() / 1_000_000.0, adValue.getCurrencyCode())); }); Log.d("Rewarded", "Ad loaded and ready"); } @Override public void onAdFailedToLoad(LoadAdError adError) { Log.e("Rewarded", "Load failed: " + adError.getMessage()); rewardedAd = null; } }); } private void showRewardedAd() { if (rewardedAd == null) { Log.d("Rewarded", "Ad not loaded yet"); loadRewardedAd(); return; } rewardedAd.show(RewardedAdActivity.this, rewardItem -> { // User earned reward int rewardAmount = rewardItem.getAmount(); String rewardType = rewardItem.getType(); Log.d("Reward", String.format( "User earned: %d %s", rewardAmount, rewardType)); // Grant reward in your app awardReward(rewardType, rewardAmount); }); } private String generateCustomData() { // Generate a nonce for server-side verification // This should be unique and tied to the user session return "user_session_" + System.currentTimeMillis(); } private void awardReward(String rewardType, int rewardAmount) { // Award coins, gems, or other in-app currency Log.d("Game", "Awarding " + rewardAmount + " " + rewardType); } @Override protected void onResume() { super.onResume(); // Load ad on resume if not already loaded if (rewardedAd == null) { loadRewardedAd(); } } } ``` -------------------------------- ### Get Child-Directed Treatment Tag Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/07-sdk-initialization-configuration.md Retrieves the child-directed treatment setting for ad requests. ```java int getTagForChildDirectedTreatment() ``` -------------------------------- ### PreloadConfiguration Instance Methods Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/09-preloading-api.md Methods to retrieve configuration details from a PreloadConfiguration object. ```APIDOC ## PreloadConfiguration Instance Methods ### Description Provides methods to access the configured ad unit ID and the number of ads to be preloaded. ### Methods #### getAdCount ```java int getAdCount() ``` Returns the buffer size, which is the number of ads to preload. **Returns**: `int` - The buffer size. #### getAdUnitId ```java String getAdUnitId() ``` Returns the ad unit ID associated with this preloading configuration. **Returns**: `String` - The ad unit identifier. ``` -------------------------------- ### Get Preloaded Ad Count Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/09-preloading-api.md Retrieve the number of ads that are preloaded and maintained in the buffer. ```java int getAdCount() ``` -------------------------------- ### Initialize PreloadConfiguration Builder Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/09-preloading-api.md Use this builder to configure preloading for a specific ad unit. You must provide the ad unit ID during initialization. ```java new PreloadConfiguration.Builder(String adUnitId) .setAdCount(int count) .setAdRequest(AdRequest request) .build() ``` -------------------------------- ### Get Ad Height Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/10-types-and-enums.md Retrieves the height of the ad size in density-independent pixels (dp). ```java int getHeight() ``` -------------------------------- ### Get Ad Width Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/10-types-and-enums.md Retrieves the width of the ad size in density-independent pixels (dp). ```java int getWidth() ``` -------------------------------- ### Initialize Mobile Ads SDK Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/README.md Initialize the Mobile Ads SDK asynchronously on a background thread. The initialization is complete when the callback is invoked. ```java new Thread(() -> { MobileAds.initialize(context, status -> { // Initialization complete }); }).start(); ``` -------------------------------- ### Get Maximum Ad Content Rating Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/07-sdk-initialization-configuration.md Retrieves the maximum content rating configured for ads. ```java String getMaxAdContentRating() ``` -------------------------------- ### Get Test Device IDs Source: https://github.com/googleads/googleads-mobile-android-examples/blob/main/_autodocs/07-sdk-initialization-configuration.md Retrieves the list of test device IDs configured for the SDK. ```java List getTestDeviceIds() ```