<br />

Rewarded interstitial ads are a format that lets you offer rewards for ads
that appear automatically during natural app transitions. Unlike rewarded ads,
users don't have to opt in to view a rewarded interstitial ad.

For more information, see
[Rewarded interstitial guidance](https://support.google.com/admob/answer/9884467).


This guide explains how to integrate rewarded interstitial ads into an Android
app.

## Before you begin

Before you continue, do the following:

- [Set up GMA Next-Gen SDK](https://developers.google.com/admob/android/next-gen/quick-start.md.txt).
- Use the test rewarded interstitial ad unit ID `ca-app-pub-3940256099942544/5354046379`.
  - When building and testing your app, make sure that you use test ads rather than live, production ads. If you don't use the test ad unit ID, Google can suspend your account.
  - Before you publish your app, replace this ID with your ad unit ID.
  - For details on GMA Next-Gen SDK test ads, see [Enable test ads](https://developers.google.com/admob/android/next-gen/test-ads.md.txt).

## Understand ad preloading (beta)

[Video](https://www.youtube.com/watch?v=gtCvIEGOwtA)

Ad preloading in GMA Next-Gen SDK automates ad loading and caching.

Ad preloading provides the following benefits:

- **Reference management**: maintains references until ads are shown.
- **Automatic reloading**: loads a new ad when one is retrieved from the cache.
- **Managed retries**: loads a new ad when one fails to load.
- **Expiration handling**: refreshes ads before expiring.
- **Cache optimization**: optimizes the cache order to deliver the highest priority ad.

> [!NOTE]
> **Note:** To load ads manually, see [Load a single rewarded interstitial ad](https://developers.google.com/admob/android/next-gen/rewarded-interstitial/single-load.md.txt).

## Start ad preloading

To begin preloading ads, call the `start` method once
when you initialize GMA Next-Gen SDK. After you call the
`start` method, GMA Next-Gen SDK automatically preloads ads
and retries failed requests for preloaded configurations.

The following example shows how to start preloading ads:


### Kotlin

```kotlin
private fun startPreloading(adUnitId: String) {
  // Call start() once after SDK initialization.
  // Preload only one ad unit per format to optimize performance.
  val adRequest = AdRequest.Builder(adUnitId).build()
  val preloadConfig = PreloadConfiguration(adRequest)
  RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig)
}
```

### Java

```java
private void startPreloading(String adUnitId) {
  // Call start() once after SDK initialization.
  // Preload only one ad unit per format to optimize performance.
  AdRequest adRequest = new AdRequest.Builder(adUnitId).build();
  PreloadConfiguration preloadConfig = new PreloadConfiguration(adRequest);
  RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig);
}
```

<br />

Replace <var class="readonly" translate="no">AD_UNIT_ID</var> with your ad unit ID.

The previous example shows how to use the ad unit ID as the preload ID. A
preload ID is a string identifier that you create to identify an ad preloading
configuration. If your app requires multiple targeting configurations for the
same ad unit ID, pass a custom string identifier.

Ad preloading doesn't support changing targeting parameters or ad requests.
If you need to change targeting parameters between requests, use
[single loading](https://developers.google.com/admob/android/next-gen/rewarded-interstitial/single-load.md.txt).

## Get and show the preloaded ad

Before showing the ad, call the `pollAd` method.
Don't store the preloaded ad object. When you call the
`pollAd` method, GMA Next-Gen SDK retrieves an available ad
and automatically preloads the next ad in the background. If no ad is
available, GMA Next-Gen SDK returns no ads.
When you have an available ad object, call the `show` method to display the ad. Use a reward listener to handle reward events. The following example shows how to retrieve and show a preloaded ad:


### Kotlin

```kotlin
private fun pollAndShowAd(activity: Activity, adUnitId: String) {
  // Polling returns the next available ad and loads another ad in the background.
  val ad = RewardedInterstitialAdPreloader.pollAd(adUnitId)
  if (ad == null) {
    Log.e(TAG, "Rewarded interstitial ad is not available.")
    return
  }

  // Interact with the ad object as needed.
  Log.d(TAG, "Rewarded interstitial ad response info: ${ad.getResponseInfo()}")
  ad.adEventCallback =
    object : RewardedInterstitialAdEventCallback {
      override fun onAdImpression() {
        Log.d(TAG, "Rewarded interstitial ad recorded an impression.")
      }
    }
  ad.show(activity) { rewardItem -> Log.d(TAG, "User earned reward: ${rewardItem.amount}") }
}
```

### Java

```java
private void pollAndShowAd(Activity activity, String adUnitId) {
  // Polling returns the next available ad and loads another ad in the background.
  final RewardedInterstitialAd ad = RewardedInterstitialAdPreloader.pollAd(adUnitId);

  // Interact with the ad object as needed.
  if (ad == null) {
    Log.e(TAG, "Rewarded interstitial ad is not available.");
    return;
  }

  Log.d(TAG, "Rewarded interstitial ad response info: " + ad.getResponseInfo());
  ad.setAdEventCallback(
      new RewardedInterstitialAdEventCallback() {
        @Override
        public void onAdImpression() {
          Log.d(TAG, "Rewarded interstitial ad recorded an impression.");
        }
      });

  // Show the ad.
  ad.show(
      activity,
      rewardItem -> {
        Log.d(TAG, "User earned reward: " + rewardItem.getAmount());
      });
}
```

<br />

When your app reaches an ad placement and can call the `show` method, call the
`pollAd` method. Don't call the
`pollAd` method in preload callbacks or after checking the
`isAdAvailable` method to hold an ad. If you need
to inspect ad metadata before showing the ad,
[read the response info](https://developers.google.com/admob/android/next-gen/rewarded-interstitial.md.txt#peek-at-ad) without removing the ad from the cache.

## Listen to ad events

Before showing the ad, listen to ad events. The following example
registers callbacks for ad events:


### Kotlin

```kotlin
private fun listenToAdEvents() {
  // Listen for ad events.
  val ad = rewardedInterstitialAd
  if (ad == null) {
    Log.e(TAG, "Rewarded interstitial ad is not ready yet.")
    return
  }

  ad.adEventCallback =
    object : RewardedInterstitialAdEventCallback {
      override fun onAdShowedFullScreenContent() {
        // Rewarded interstitial ad did show.
      }

      override fun onAdDismissedFullScreenContent() {
        // Rewarded interstitial ad did dismiss.
        rewardedInterstitialAd = null
      }

      override fun onAdFailedToShowFullScreenContent(
        fullScreenContentError: FullScreenContentError
      ) {
        // Rewarded interstitial ad failed to show.
        Log.e(TAG, "Rewarded interstitial ad failed to show: ${fullScreenContentError.message}")
      }

      override fun onAdImpression() {
        // Rewarded interstitial ad did record an impression.
      }

      override fun onAdClicked() {
        // Rewarded interstitial ad did record a click.
      }
    }
}
```

### Java

```java
private void listenToAdEvents() {
  // Listen for ad events.
  if (rewardedInterstitialAd == null) {
    Log.e(TAG, "Rewarded interstitial ad is not ready yet.");
    return;
  }

  rewardedInterstitialAd.setAdEventCallback(
      new RewardedInterstitialAdEventCallback() {
        @Override
        public void onAdShowedFullScreenContent() {
          // Rewarded interstitial ad did show.
        }

        @Override
        public void onAdDismissedFullScreenContent() {
          // Rewarded interstitial ad did dismiss.
          rewardedInterstitialAd = null;
        }

        @Override
        public void onAdFailedToShowFullScreenContent(
            @NonNull FullScreenContentError fullScreenContentError) {
          // Rewarded interstitial ad failed to show.
          Log.e(
              TAG,
              "Rewarded interstitial ad failed to show: " + fullScreenContentError.getMessage());
        }

        @Override
        public void onAdImpression() {
          // Rewarded interstitial ad did record an impression.
        }

        @Override
        public void onAdClicked() {
          // Rewarded interstitial ad did record a click.
        }
      });
}
```

<br />

## Optional: Validate server-side verification (SSV) callbacks

To pass user and application context in
[server-side verification](https://developers.google.com/admob/android/next-gen/ssv.md.txt)
(SSV) callbacks, set
verification options on the ad object before showing the ad. Because SSV
callbacks arrive at your server from Google without session state,
attach the following optional strings. Google forwards these strings
unchanged as signed query parameters in the SSV callback.

- `user_id` query parameter: Identifies the user to credit, such as an internal account ID.
- `custom_data` query parameter: Carries app data, such as the reward placement, game level, or a server-generated nonce.

If you don't set a value, Google omits that query parameter from the SSV
callback.

The following example sets custom data on an ad object before
showing the ad:


### Kotlin

```kotlin
RewardedInterstitialAd.load(
  context,
  AD_UNIT_ID,
  AdRequest.Builder().build(),
  object : RewardedInterstitialAdLoadCallback() {
    override fun onAdLoaded(ad: RewardedInterstitialAd) {
      rewardedInterstitialAd = ad
val options =
ServerSideVerificationOptions.Builder().setCustomData("SAMPLE_CUSTOM_DATA_STRING").build()
rewardedInterstitialAd?.setServerSideVerificationOptions(options)
}
},
)
```

### Java

```java
RewardedInterstitialAd.load(
    context,
    AD_UNIT_ID,
    new AdRequest.Builder().build(),
    new RewardedInterstitialAdLoadCallback() {
      @Override
      public void onAdLoaded(RewardedInterstitialAd ad) {
        rewardedInterstitialAd = ad;
ServerSideVerificationOptions options =
new ServerSideVerificationOptions.Builder()
.setCustomData("SAMPLE_CUSTOM_DATA_STRING")
.build();
rewardedInterstitialAd.setServerSideVerificationOptions(options);
      }
    });
```

<br />

Replace `SAMPLE_CUSTOM_DATA_STRING` with your custom
data.

Key point: The `custom_data` query parameter is
[percent-encoded](https://en.wikipedia.org/wiki/Percent-encoding). Before you
parse the value, URL-decode the string on your server and verify the callback
signature before trusting the `user_id` or `custom_data` query parameters.


## Optional: Listen to preloading events

When you start preloading ads, register for preload events to get notified
when ads are preloaded successfully, fail to preload, or the ad cache is
exhausted.

The following example shows how to register for preloading ad events:


### Kotlin

```kotlin
val preloadCallback =
  // [Important] Don't call ad preloader start() or pollAd() within the PreloadCallback.
  object : PreloadCallback {
    override fun onAdFailedToPreload(preloadId: String, adError: LoadAdError) {
      Log.d(
        TAG,
        "Rewarded interstitial preload ad $preloadId failed to load with error: ${adError.message}",
      )
    }

    override fun onAdsExhausted(preloadId: String) {
      Log.i(TAG, "Rewarded interstitial preload ad $preloadId is not available")
      // [Important] Don't call ad preloader start() or pollAd() from onAdsExhausted.
    }

    override fun onAdPreloaded(preloadId: String, responseInfo: ResponseInfo) {
      Log.i(TAG, "Rewarded interstitial preload ad $preloadId is available")
    }
  }
val adRequest = AdRequest.Builder(adUnitId).build()
val preloadConfig = PreloadConfiguration(adRequest)
RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig, preloadCallback)
```

### Java

```java
PreloadCallback preloadCallback =
    // [Important] Don't call ad preloader start() or pollAd() within the PreloadCallback.
    new PreloadCallback() {
      @Override
      public void onAdFailedToPreload(@NonNull String preloadId, @NonNull LoadAdError adError) {
        Log.d(
            TAG,
            String.format(
                "Rewarded interstitial preload ad %s failed to load with error: %s",
                preloadId, adError.getMessage()));
        // [Optional] Get the error response info for additional details.
        // ResponseInfo responseInfo = adError.getResponseInfo();
      }

      @Override
      public void onAdsExhausted(@NonNull String preloadId) {
        Log.i(TAG, "Rewarded interstitial preload ad " + preloadId + " is not available");
        // [Important] Don't call ad preloader start() or pollAd() from onAdsExhausted.
      }

      @Override
      public void onAdPreloaded(@NonNull String preloadId, @NonNull ResponseInfo responseInfo) {
        Log.i(TAG, "Rewarded interstitial preload ad " + preloadId + " is available");
      }
    };
AdRequest adRequest = new AdRequest.Builder(adUnitId).build();
PreloadConfiguration preloadConfig = new PreloadConfiguration(adRequest);
RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig, preloadCallback);
```

<br />

When an ad fails to load, GMA Next-Gen SDK automatically preloads ads and retries
failed requests for preloaded configurations. Don't invoke manual load
requests in failure callbacks. In preloading event callback methods, don't
call the `pollAd`, `destroy`, or
`start` methods. Calling these methods in callbacks
can invoke recursive load loops.

## Optional: Check for ad availability

If you need to know whether an ad is available, check for ad availability. The
following example checks whether a preloaded ad is available:


### Kotlin

```kotlin
private fun isAdAvailable(adUnitId: String): Boolean {
  return RewardedInterstitialAdPreloader.isAdAvailable(adUnitId)
}
```

### Java

```java
private boolean isAdAvailable(String adUnitId) {
  return RewardedInterstitialAdPreloader.isAdAvailable(adUnitId);
}
```

<br />

## Optional: Set the buffer size

The buffer size controls the number of preloaded ads held in memory. By
default, Google optimizes buffer size to balance memory consumption and ad
serving latency. You can set a custom buffer size to increase or decrease the
number of ads kept in memory. We recommend a buffer size of two preloaded ads.
If most of your traffic comes from low-memory devices, reduce the buffer size.

The following example shows how to set a buffer size:


### Kotlin

```kotlin
private fun setBufferSize(adUnitId: String) {
  val adRequest = AdRequest.Builder(adUnitId).build()
  // Define a PreloadConfiguration and set the buffer size to 2 preloaded ads.
  val preloadConfig = PreloadConfiguration(adRequest, bufferSize = 2)
  RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig)
}
```

### Java

```java
private void setBufferSize(String adUnitId) {
  AdRequest adRequest = new AdRequest.Builder(adUnitId).build();
  // Define a PreloadConfiguration and set the buffer size to 2 preloaded ads.
  PreloadConfiguration preloadConfig = new PreloadConfiguration(adRequest, 2);
  RewardedInterstitialAdPreloader.start(adUnitId, preloadConfig);
}
```

<br />

### Preload cache limits

GMA Next-Gen SDK enforces an app-wide limit on the total number of preloaded ads
across all ad units and preload IDs:

- Default limit: Google holds a maximum of six preloaded ads in memory. This limit is shared across all formats and preload IDs.
- We recommend keeping a buffer size of two for each preload ID.

> [!NOTE]
> **Note:** If your app can benefit from an increased app-wide limit, contact your account manager to request an increase.

## Optional: Stop preloading ads

Keep preloading active while your app serves ads. During this time, don't the
`destroy` method. If you don't need to show ads for a
specific preload ID again in the session, you can stop preloading ads. To stop
loading ads for a specific preload ID, call the `destroy`
method with a preload ID. Calling the `destroy` method
removes all preloaded ads associated with the preload ID from the cache.

The following example shows how to stop preloading ads:


### Kotlin

```kotlin
private fun stopPreloading(adUnitId: String) {
  // Stops the preloading and destroy preloaded ads.
  RewardedInterstitialAdPreloader.destroy(adUnitId)
}
```

### Java

```java
private void stopPreloading(String adUnitId) {
  // Stops the preloading and destroy preloaded ads.
  RewardedInterstitialAdPreloader.destroy(adUnitId);
}
```

<br />

## Optional: Read the response info

Read the next preloaded ad's response info without removing the ad from the
cache. If you need to inspect ad metadata before you show an ad,
read the response info instead of calling the `pollAd`
method.

The following example shows how to read the next preloaded ad response info:


### Kotlin

```kotlin
val responseInfo = RewardedInterstitialAdPreloader.peekAdResponseInfo(preloadId)
if (responseInfo == null) {
  Log.e(TAG, "Failed to peek ad response info.")
  return
}

Log.d(TAG, "Peeked ad response ID: ${responseInfo.responseId}")
```

### Java

```java
ResponseInfo responseInfo = RewardedInterstitialAdPreloader.peekAdResponseInfo(preloadId);
if (responseInfo == null) {
  Log.e(TAG, "Failed to peek ad response info.");
  return;
}

Log.d(TAG, "Peeked ad response ID: " + responseInfo.getResponseId());
```

<br />