Google Mobile Ads Android Examples (Legacy)

repository·main·Indexed 23 days ago

https://github.com/googleads/googleads-mobile-android-examples

Developer samples and code snippets for the legacy Google Mobile Ads SDK for Android (com.google.android.gms:play-services-ads). Includes implementations for AdMob Rewarded Ads Server-Side Verification (SSV) using Java Spring Boot, AdListener event handling, LoadAdError diagnostics, and AdManagerAdView manual impression management.

Tokens
1.8K
Snippets
5
Records
10
Agent score
84%

What's inside googleads-mobile-android-examples

  1. Use the correct SDK for Google Mobile Ads on Android

    main

    This repository contains developer samples and snippets specifically for the legacy Google Mobile Ads SDK (com.google.android.gms:play-services-ads).

    If you are starting a new project or want to use the latest features, you should use the GMA Next-Gen SDK (com.google.android.libraries.ads.mobile.sdk:ads-mobile-sdk) instead. Samples for the Next-Gen SDK can be found in the GMA Next-Gen SDK repository.

  2. Understand Google AdMob Rewarded Ads Server-Side Verification (SSV)

    main
    Server-side verification (SSV) callbacks are URL requests sent by Google to your external system to notify it that a user has interacted with a rewarded video ad. Using SSV provides an extra layer of security by preventing users from spoofing client-side reward callbacks. The callback contains query parameters expanded by Google, which your server should verify to ensure the reward is legitimate.
  3. Test SSV signature and message verification

    main

    To test the verification logic locally, send a GET request to the /verify endpoint. The request must include the data to verify, the signature, and the key ID as query parameters.

    Endpoint URL Pattern: localhost:8080/verify?<dataToVerify>&signature=<signature>&key_id=<key_id>

    Successful Response Format: A successful verification returns a JSON object containing the signature, the original payload, the key ID used, and a verified boolean.

    {
      "sig": "ME...Z1c",
      "payload": "ad_network=54...55&ad_unit=12345678&reward_amount=10&reward_item=coins &timestamp=150777823&transaction_id=12...DEF&user_id=1234567",
      "key_id": "1268887",
      "verified": "true"
    }
  4. Manage manual impressions in AdManagerAdView

    main

    If you are using AdManagerAdView, you can control how impressions are counted. You can enable manual impression counting and then record them explicitly.

    1. Enable manual impressions: adManagerAdView.setManualImpressionsEnabled(true)
    2. Record an impression: adManagerAdView.recordManualImpression()
  5. Destroy a Banner ad

    main

    To prevent memory leaks and properly clean up resources, you should destroy your banner ads when they are no longer needed. This involves removing the AdView from its parent view hierarchy and calling destroy() on the view itself.

    if (adView != null) {
        // Remove banner from view hierarchy.
        View parentView = (View) adView.getParent();
        if (parentView instanceof ViewGroup) {
            ((ViewGroup) parentView).removeView(adView);
        }
    
        // Destroy the banner ad resources.
        adView.destroy();
    }
    
    // Drop reference to the banner ad.
    adView = null;
    public void destroyBanner() {
        if (adView != null) {
          View parentView = (View) adView.getParent();
          if (parentView instanceof ViewGroup) {
            ((ViewGroup) parentView).removeView(adView);
          }
          adView.destroy();
        }
        adView = null;
    }
  6. Handle Ad events with AdListener

    main

    To respond to ad lifecycle events (such as loading, clicking, or failing to load), attach an AdListener to your AdView using setAdListener(). This allows you to execute custom logic when specific events occur.

    Key methods in AdListener include:

    • onAdLoaded(): Called when an ad finishes loading.
    • onAdFailedToLoad(LoadAdError): Called when an ad request fails.
    • onAdClicked(): Called when the user clicks on an ad.
    • onAdOpened(): Called when an ad opens an overlay.
    • onAdClosed(): Called when the user returns to the app after tapping an ad.
    • onAdImpression(): Called when an impression is recorded.
    adView.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            // Code to be executed when an ad finishes loading.
        }
    
        @Override
        public void onAdFailedToLoad(@NonNull LoadAdError adError) {
            // Code to be executed when an ad request fails.
        }
        // ... other overrides
    });
  7. Handle App Events with AppEventListener

    main

    AdManagerAdView allows you to set an AppEventListener to listen for custom app events. When an event occurs, the onAppEvent(@NonNull String name, @NonNull String info) method is triggered.

    Implement the AppEventListener interface and use the name and info parameters to determine how your application should react to the event.

    @Override
    public void onAppEvent(@NonNull String name, @NonNull String info) {
        if (name.equals("color")) {
          switch (info) {
            case "green":
              // Set background color to green.
              break;
            case "blue":
              // Set background color to blue.
              break;
            default:
              // Set background color to black.
              break;
          }
        }
    }
  8. Handle Ad load errors with LoadAdError

    main

    When an ad fails to load, the onAdFailedToLoad callback provides a LoadAdError object. You can use this object to diagnose the failure by extracting the following information:

    • getDomain(): The domain from which the error originated.
    • getCode(): The error code (refer to the AdRequest constant summary for details).
    • getMessage(): A human-readable error message (e.g., "Account not approved yet").
    • getResponseInfo(): Additional response information about the request.
    • getCause(): The underlying AdError cause, if available.
    • toString(): A string representation containing all the above information.
    @Override
    public void onAdFailedToLoad(@NonNull LoadAdError adError) {
        String errorDomain = adError.getDomain();
        int errorCode = adError.getCode();
        String errorMessage = adError.getMessage();
        ResponseInfo responseInfo = adError.getResponseInfo();
        AdError cause = adError.getCause();
        Log.d("Ads", adError.toString());
    }