Guide
Full-screen backfill
When your mediation has no interstitial or rewarded ad, show NGA's in that moment. Your mediation always comes first, so NGA never takes a moment it could fill.
The rule #
Your code keeps the rule, because the SDK cannot see your mediation. A moment is a point where your game would show an ad.
- Load NGA's placement only from your mediation's load-failed callback. Never ahead of a failure.
- At the moment of the show, your mediation comes first. If its ad is ready, show it. Show NGA's only while your mediation's latest load has failed and NGA's ad
isReady(). - Keep retrying your mediation. When it loads again, it has the next moment.
A remove-ads purchase needs no NGA code here: NGA's ad is loaded only where your mediation's would have been shown, so your game's own remove-ads rule covers those moments.
The order at startup #
- Initialize NGA before your mediation, as on Initialize, or later once your consent platform has answered, but still before the mediation. NGA's capture of MAX and LevelPlay revenue starts there, so an ad your mediation shows right after is recorded.
- Initialize your mediation as its own documentation says, in the same place or in your first screen.
- Create and load the mediation's ads after its init is done (Init is done when, below). The examples load in the screen's
onCreate,viewDidLoadorStart, which works only if init finished before the screen opened. If the same screen starts the mediation:- Create the mediation's ad and load it the first time in the mediation's init callback.
- Check that the ad exists before you show or destroy it. The show moment can come before init is done.
The examples' helpers belong to the screen and are its load callbacks, so the SDK holds the screen, through them, for up to 30 minutes; for a screen that closes often, keep the helper app-wide (Callback ownership). For the native banner and a backfill on one screen, see Native cross-promo.
What the player gets #
- One of your other games' videos, full screen, with its endcard if you supplied one.
- A way out. A close button always appears, even when an ad stalls or fails to play, and back works on Android once the close is available. An interstitial's close appears within seconds; a rewarded ad's, when the reward is earned.
- The store only on a tap. Nothing opens the store without the player's tap.
- Your game, as it was. The ad runs in NGA's own full-screen Activity or view controller. Its sound follows
setMuted, and your audio session is restored when it closes.
Pause and resume #
Pause your game's loop, timers and sound right before you call show. Resume on onClosed or onShowFailed, the two callbacks that end every show. Do not wait for onShowStarted. It marks the impression, and is called a second or more after show, or never if the impression does not count.
| Unity | on Android | on iOS |
|---|---|---|
| While the ad is in front | Unity pauses itself | nothing is paused |
| The show's callbacks arrive | after the ad closes, in their original order | during the ad |
OnApplicationPause |
true as the ad opens, false as it closes. That resume is not a return from the background |
— |
Either way, pause the game yourself before Show, and do not depend on any callback arriving while the ad is on screen.
Your mediation #
Initialize your mediation as its own documentation says, before the first load. The examples were built and checked with these versions, which are not the oldest that work: they use only the calls shown (for LevelPlay, its ad-unit API, LevelPlayInterstitialAd and LevelPlayRewardedAd), so an older version with those calls compiles the same code.
| AppLovin MAX | Unity LevelPlay | Google AdMob | |
|---|---|---|---|
| Android | com.applovin:applovin-sdk:13.7.0 |
com.unity3d.ads-mediation:mediation-sdk:9.7.0 |
com.google.android.gms:play-services-ads:25.5.0 (see Requirements) |
| iOS | the AppLovinSDK Swift package 13.7.0 |
LevelPlay-Swift-Package 9.7.0 (module IronSource) |
the GoogleMobileAds Swift package 13.12.0 |
| Unity | the MAX Unity plugin 8.6.6 | com.unity.services.levelplay 9.6.0 |
the Google Mobile Ads Unity plugin 11.6.0 |
| Init is done when | Android: AppLovinSdk.getInstance(context).initialize(config, listener) completes. iOS: ALSdk.shared().initialize(with:completionHandler:) completes. Unity: MaxSdkCallbacks.OnSdkInitializedEvent has fired |
its init success: LevelPlayInitListener.onInitSuccess (Android), LevelPlay.initWith's completion with no error (iOS), LevelPlay.OnInitSuccess (Unity) |
MobileAds.initialize completes |
| Setup guide | Unity · Android · iOS | Unity · Android · iOS | Unity · Android · iOS |
| Rewarded ad to wire | Unity: MaxSdkCallbacks.Rewarded.OnAdLoadedEvent and OnAdLoadFailedEvent. Android: MaxRewardedAd.getInstance(adUnitId) with a MaxRewardedAdListener. iOS: MARewardedAd.shared(withAdUnitIdentifier:) |
LevelPlayRewardedAd (Unity, Android), LPMRewardedAd (iOS) |
RewardedAd.load |
| Note | the Android example uses MAX 13's one-argument MaxInterstitialAd(adUnitId); AppLovin's page still shows the two-argument form, deprecated since 13.6 |
— | on iOS, Google Mobile Ads 13.12 reports paid events to the ad's FullScreenContentDelegate, so the example's delegate forwards them to ad revenue |
Interstitial #
Choose your mediation; the choice holds on this page. Each example is one screen that owns the mediation's interstitial and hands NGA's half to InterstitialBackfill, the helper after the examples, which keeps the rule.
AppLovin MAX
Unity (C#)
using System;
using System.Collections;
using UnityEngine;
public class MaxBackfill : MonoBehaviour
{
const string MaxAdUnit = "YOUR_MAX_INTERSTITIAL_AD_UNIT";
readonly InterstitialBackfill nga = new InterstitialBackfill(); // InterstitialBackfill.cs, below
int maxRetry;
void Start() // once MAX has initialized (MaxSdkCallbacks.OnSdkInitializedEvent has fired)
{
MaxSdkCallbacks.Interstitial.OnAdLoadedEvent += OnMaxLoaded;
MaxSdkCallbacks.Interstitial.OnAdLoadFailedEvent += OnMaxLoadFailed;
MaxSdkCallbacks.Interstitial.OnAdHiddenEvent += OnMaxHidden;
MaxSdkCallbacks.Interstitial.OnAdDisplayFailedEvent += OnMaxDisplayFailed;
MaxSdk.LoadInterstitial(MaxAdUnit);
}
void OnDestroy()
{
MaxSdkCallbacks.Interstitial.OnAdLoadedEvent -= OnMaxLoaded;
MaxSdkCallbacks.Interstitial.OnAdLoadFailedEvent -= OnMaxLoadFailed;
MaxSdkCallbacks.Interstitial.OnAdHiddenEvent -= OnMaxHidden;
MaxSdkCallbacks.Interstitial.OnAdDisplayFailedEvent -= OnMaxDisplayFailed;
}
// Call at the moment your game would show an interstitial.
public void ShowInterstitial()
{
if (MaxSdk.IsInterstitialReady(MaxAdUnit))
{
PauseGame();
MaxSdk.ShowInterstitial(MaxAdUnit); // the mediation always comes first
}
else if (!nga.TryShow(PauseGame, AfterNga)) ContinueGame(); // MAX has no fill and NGA has nothing ready
}
// MAX
void OnMaxLoaded(string adUnitId, MaxSdkBase.AdInfo info) { nga.OnMediationLoaded(); maxRetry = 0; }
void OnMaxLoadFailed(string adUnitId, MaxSdkBase.ErrorInfo error)
{
if (this == null) return;
nga.OnMediationLoadFailed();
maxRetry++;
StartCoroutine(RetryMax((float)Math.Pow(2, Math.Min(6, maxRetry)))); // AppLovin's backoff
}
void OnMaxHidden(string adUnitId, MaxSdkBase.AdInfo info) { MaxSdk.LoadInterstitial(MaxAdUnit); ResumeGame(); ContinueGame(); }
void OnMaxDisplayFailed(string adUnitId, MaxSdkBase.ErrorInfo error, MaxSdkBase.AdInfo info)
{
MaxSdk.LoadInterstitial(MaxAdUnit);
ResumeGame();
ContinueGame();
}
IEnumerator RetryMax(float seconds)
{
yield return new WaitForSecondsRealtime(seconds);
if (this != null) MaxSdk.LoadInterstitial(MaxAdUnit);
}
void AfterNga()
{
if (this == null) return;
ResumeGame();
ContinueGame();
}
// Your game's own code.
void PauseGame() { }
void ResumeGame() { }
void ContinueGame() { }
}
Android (Kotlin)
import android.app.Activity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxAdListener
import com.applovin.mediation.MaxError
import com.applovin.mediation.ads.MaxInterstitialAd
import kotlin.math.min
import kotlin.math.pow
// MAX is initialized, as AppLovin's documentation says, before this screen opens.
class MaxBackfillActivity : Activity(), MaxAdListener {
private val handler = Handler(Looper.getMainLooper())
private val nga = InterstitialBackfill() // InterstitialBackfill.kt, below
private lateinit var maxAd: MaxInterstitialAd
private var maxRetry = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
maxAd = MaxInterstitialAd(MAX_AD_UNIT)
maxAd.setListener(this)
maxAd.loadAd()
}
override fun onDestroy() {
handler.removeCallbacksAndMessages(null)
maxAd.destroy()
super.onDestroy()
}
// Call at the moment your game would show an interstitial.
fun showInterstitial() {
if (maxAd.isReady) {
pauseGame()
maxAd.showAd(this) // the mediation always comes first
} else if (!nga.tryShow(this, ::pauseGame, ::afterNga)) {
continueGame() // MAX has no fill and NGA has nothing ready
}
}
// MaxAdListener
override fun onAdLoaded(ad: MaxAd) {
nga.onMediationLoaded()
maxRetry = 0
}
override fun onAdLoadFailed(adUnitId: String, error: MaxError) {
if (isDestroyed) return
nga.onMediationLoadFailed()
maxRetry++
val delayMs = 1000L * 2.0.pow(min(6, maxRetry)).toLong() // AppLovin's backoff
handler.postDelayed({ maxAd.loadAd() }, delayMs)
}
override fun onAdDisplayed(ad: MaxAd) {}
override fun onAdClicked(ad: MaxAd) {}
override fun onAdHidden(ad: MaxAd) {
maxAd.loadAd()
resumeGame()
continueGame()
}
override fun onAdDisplayFailed(ad: MaxAd, error: MaxError) {
maxAd.loadAd()
resumeGame()
continueGame()
}
private fun afterNga() {
if (isDestroyed) return
resumeGame()
continueGame()
}
// Your game's own code.
private fun pauseGame() {}
private fun resumeGame() {}
private fun continueGame() {}
companion object {
const val MAX_AD_UNIT = "YOUR_MAX_INTERSTITIAL_AD_UNIT"
}
}
iOS (Swift)
import UIKit
import AppLovinSDK
// MAX is initialized, as AppLovin's documentation says, before this screen opens.
final class MaxBackfillViewController: UIViewController, MAAdDelegate {
private let maxAd = MAInterstitialAd(adUnitIdentifier: "YOUR_MAX_INTERSTITIAL_AD_UNIT")
private let nga = InterstitialBackfill() // InterstitialBackfill.swift, below
private var maxRetry = 0.0
override func viewDidLoad() {
super.viewDidLoad()
maxAd.delegate = self
maxAd.load()
}
// Call at the moment your game would show an interstitial.
func showInterstitial() {
if maxAd.isReady {
pauseGame()
maxAd.show() // the mediation always comes first
} else if !nga.tryShow(from: self, pauseGame: pauseGame, afterAd: afterNga) {
continueGame() // MAX has no fill and NGA has nothing ready
}
}
// MAAdDelegate
func didLoad(_ ad: MAAd) {
nga.onMediationLoaded()
maxRetry = 0
}
func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError) {
nga.onMediationLoadFailed()
maxRetry += 1
let delay = pow(2.0, min(6.0, maxRetry)) // AppLovin's backoff
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in self?.maxAd.load() }
}
func didDisplay(_ ad: MAAd) {}
func didClick(_ ad: MAAd) {}
func didHide(_ ad: MAAd) {
maxAd.load()
resumeGame()
continueGame()
}
func didFail(toDisplay ad: MAAd, withError error: MAError) {
maxAd.load()
resumeGame()
continueGame()
}
private func afterNga() {
resumeGame()
continueGame()
}
// Your game's own code.
private func pauseGame() {}
private func resumeGame() {}
private func continueGame() {}
}
Unity LevelPlay
Unity (C#)
using System;
using System.Collections;
using UnityEngine;
using Unity.Services.LevelPlay;
public class LevelPlayBackfill : MonoBehaviour
{
const string LevelPlayAdUnit = "YOUR_LEVELPLAY_INTERSTITIAL_AD_UNIT";
readonly InterstitialBackfill nga = new InterstitialBackfill(); // InterstitialBackfill.cs, below
LevelPlayInterstitialAd levelPlayAd;
int levelPlayRetry;
// Call once LevelPlay.OnInitSuccess has fired.
public void StartAds()
{
levelPlayAd = new LevelPlayInterstitialAd(LevelPlayAdUnit);
levelPlayAd.OnAdLoaded += OnLevelPlayLoaded;
levelPlayAd.OnAdLoadFailed += OnLevelPlayLoadFailed;
levelPlayAd.OnAdClosed += OnLevelPlayClosed;
levelPlayAd.OnAdDisplayFailed += OnLevelPlayDisplayFailed;
levelPlayAd.LoadAd();
}
void OnDestroy() { levelPlayAd?.DestroyAd(); }
// Call at the moment your game would show an interstitial.
public void ShowInterstitial()
{
if (levelPlayAd != null && levelPlayAd.IsAdReady())
{
PauseGame();
levelPlayAd.ShowAd(); // the mediation always comes first
}
else if (!nga.TryShow(PauseGame, AfterNga)) ContinueGame(); // LevelPlay has no fill and NGA has nothing ready
}
// LevelPlay
void OnLevelPlayLoaded(LevelPlayAdInfo info) { nga.OnMediationLoaded(); levelPlayRetry = 0; }
void OnLevelPlayLoadFailed(LevelPlayAdError error)
{
if (this == null) return;
nga.OnMediationLoadFailed();
levelPlayRetry++;
StartCoroutine(RetryLevelPlay((float)Math.Pow(2, Math.Min(6, levelPlayRetry))));
}
void OnLevelPlayClosed(LevelPlayAdInfo info) { levelPlayAd.LoadAd(); ResumeGame(); ContinueGame(); }
void OnLevelPlayDisplayFailed(LevelPlayAdInfo info, LevelPlayAdError error)
{
levelPlayAd.LoadAd();
ResumeGame();
ContinueGame();
}
IEnumerator RetryLevelPlay(float seconds)
{
yield return new WaitForSecondsRealtime(seconds);
if (this != null) levelPlayAd.LoadAd();
}
void AfterNga()
{
if (this == null) return;
ResumeGame();
ContinueGame();
}
// Your game's own code.
void PauseGame() { }
void ResumeGame() { }
void ContinueGame() { }
}
Android (Kotlin)
import android.app.Activity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import com.unity3d.mediation.LevelPlayAdError
import com.unity3d.mediation.LevelPlayAdInfo
import com.unity3d.mediation.interstitial.LevelPlayInterstitialAd
import com.unity3d.mediation.interstitial.LevelPlayInterstitialAdListener
import kotlin.math.min
import kotlin.math.pow
// LevelPlay has initialized (LevelPlayInitListener.onInitSuccess) before this screen opens.
class LevelPlayBackfillActivity : Activity(), LevelPlayInterstitialAdListener {
private val handler = Handler(Looper.getMainLooper())
private val nga = InterstitialBackfill() // InterstitialBackfill.kt, below
private lateinit var levelPlayAd: LevelPlayInterstitialAd
private var levelPlayRetry = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
levelPlayAd = LevelPlayInterstitialAd(LEVELPLAY_AD_UNIT)
levelPlayAd.setListener(this)
levelPlayAd.loadAd()
}
override fun onDestroy() {
handler.removeCallbacksAndMessages(null)
super.onDestroy()
}
// Call at the moment your game would show an interstitial.
fun showInterstitial() {
if (levelPlayAd.isAdReady()) {
pauseGame()
levelPlayAd.showAd(this) // the mediation always comes first
} else if (!nga.tryShow(this, ::pauseGame, ::afterNga)) {
continueGame() // LevelPlay has no fill and NGA has nothing ready
}
}
// LevelPlayInterstitialAdListener
override fun onAdLoaded(adInfo: LevelPlayAdInfo) {
nga.onMediationLoaded()
levelPlayRetry = 0
}
override fun onAdLoadFailed(error: LevelPlayAdError) {
if (isDestroyed) return
nga.onMediationLoadFailed()
levelPlayRetry++
val delayMs = 1000L * 2.0.pow(min(6, levelPlayRetry)).toLong()
handler.postDelayed({ levelPlayAd.loadAd() }, delayMs)
}
override fun onAdDisplayed(adInfo: LevelPlayAdInfo) {}
override fun onAdDisplayFailed(error: LevelPlayAdError, adInfo: LevelPlayAdInfo) {
levelPlayAd.loadAd()
resumeGame()
continueGame()
}
override fun onAdClicked(adInfo: LevelPlayAdInfo) {}
override fun onAdClosed(adInfo: LevelPlayAdInfo) {
levelPlayAd.loadAd()
resumeGame()
continueGame()
}
override fun onAdInfoChanged(adInfo: LevelPlayAdInfo) {}
private fun afterNga() {
if (isDestroyed) return
resumeGame()
continueGame()
}
// Your game's own code.
private fun pauseGame() {}
private fun resumeGame() {}
private fun continueGame() {}
companion object {
const val LEVELPLAY_AD_UNIT = "YOUR_LEVELPLAY_INTERSTITIAL_AD_UNIT"
}
}
iOS (Swift)
import UIKit
import IronSource
// LevelPlay has initialized (LevelPlay.initWith's completion with no error) before this screen opens.
final class LevelPlayBackfillViewController: UIViewController, LPMInterstitialAdDelegate {
private let levelPlayAd = LPMInterstitialAd(adUnitId: "YOUR_LEVELPLAY_INTERSTITIAL_AD_UNIT")
private let nga = InterstitialBackfill() // InterstitialBackfill.swift, below
private var levelPlayRetry = 0.0
override func viewDidLoad() {
super.viewDidLoad()
levelPlayAd.setDelegate(self)
levelPlayAd.loadAd()
}
// Call at the moment your game would show an interstitial.
func showInterstitial() {
if levelPlayAd.isAdReady() {
pauseGame()
levelPlayAd.showAd(viewController: self, placementName: nil) // the mediation always comes first
} else if !nga.tryShow(from: self, pauseGame: pauseGame, afterAd: afterNga) {
continueGame() // LevelPlay has no fill and NGA has nothing ready
}
}
// LPMInterstitialAdDelegate
func didLoadAd(with adInfo: LPMAdInfo) {
nga.onMediationLoaded()
levelPlayRetry = 0
}
func didFailToLoadAd(withAdUnitId adUnitId: String, error: Error) {
nga.onMediationLoadFailed()
levelPlayRetry += 1
let delay = pow(2.0, min(6.0, levelPlayRetry))
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in self?.levelPlayAd.loadAd() }
}
func didDisplayAd(with adInfo: LPMAdInfo) {}
func didFailToDisplayAd(with adInfo: LPMAdInfo, error: Error) {
levelPlayAd.loadAd()
resumeGame()
continueGame()
}
func didCloseAd(with adInfo: LPMAdInfo) {
levelPlayAd.loadAd()
resumeGame()
continueGame()
}
private func afterNga() {
resumeGame()
continueGame()
}
// Your game's own code.
private func pauseGame() {}
private func resumeGame() {}
private func continueGame() {}
}
Google AdMob
Unity (C#)
using System;
using System.Collections;
using UnityEngine;
using GoogleMobileAds.Api;
using GoogleMobileAds.Common;
public class AdMobBackfill : MonoBehaviour
{
const string AdMobAdUnit = "YOUR_ADMOB_INTERSTITIAL_AD_UNIT";
readonly InterstitialBackfill nga = new InterstitialBackfill(); // InterstitialBackfill.cs, below
InterstitialAd adMobAd;
int adMobRetry;
void Start() { LoadAdMob(); } // after MobileAds.Initialize
void OnDestroy() { adMobAd?.Destroy(); }
void LoadAdMob()
{
InterstitialAd.Load(AdMobAdUnit, new AdRequest(), (ad, error) =>
// Google Mobile Ads may call back off Unity's main thread.
MobileAdsEventExecutor.ExecuteInUpdate(() => OnAdMobLoad(ad, error)));
}
void OnAdMobLoad(InterstitialAd ad, LoadAdError error)
{
if (this == null) return;
if (ad != null && error == null)
{
adMobAd = ad;
nga.OnMediationLoaded();
adMobRetry = 0;
ad.OnAdFullScreenContentClosed += () => MobileAdsEventExecutor.ExecuteInUpdate(AfterAdMob);
ad.OnAdFullScreenContentFailed += e => MobileAdsEventExecutor.ExecuteInUpdate(AfterAdMob);
return;
}
nga.OnMediationLoadFailed();
adMobRetry++;
StartCoroutine(RetryAdMob((float)Math.Pow(2, Math.Min(6, adMobRetry))));
}
IEnumerator RetryAdMob(float seconds)
{
yield return new WaitForSecondsRealtime(seconds);
if (this != null) LoadAdMob();
}
// Call at the moment your game would show an interstitial.
public void ShowInterstitial()
{
if (adMobAd != null && adMobAd.CanShowAd())
{
PauseGame();
adMobAd.Show(); // the mediation always comes first
}
else if (!nga.TryShow(PauseGame, AfterNga)) ContinueGame(); // AdMob has no fill and NGA has nothing ready
}
void AfterAdMob()
{
adMobAd?.Destroy();
adMobAd = null;
LoadAdMob();
ResumeGame();
ContinueGame();
}
void AfterNga()
{
if (this == null) return;
ResumeGame();
ContinueGame();
}
// Your game's own code.
void PauseGame() { }
void ResumeGame() { }
void ContinueGame() { }
}
Android (Kotlin)
import android.app.Activity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
import kotlin.math.min
import kotlin.math.pow
// Google Mobile Ads is initialized, as Google's documentation says, before this screen opens.
class AdMobBackfillActivity : Activity() {
private val handler = Handler(Looper.getMainLooper())
private val nga = InterstitialBackfill() // InterstitialBackfill.kt, below
private var adMobAd: InterstitialAd? = null
private var adMobRetry = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
loadAdMob()
}
override fun onDestroy() {
handler.removeCallbacksAndMessages(null)
super.onDestroy()
}
private fun loadAdMob() {
InterstitialAd.load(
this,
ADMOB_AD_UNIT,
AdRequest.Builder().build(),
object : InterstitialAdLoadCallback() {
override fun onAdLoaded(ad: InterstitialAd) {
adMobAd = ad
nga.onMediationLoaded()
adMobRetry = 0
ad.fullScreenContentCallback = object : FullScreenContentCallback() {
override fun onAdDismissedFullScreenContent() = afterAdMob()
override fun onAdFailedToShowFullScreenContent(adError: AdError) = afterAdMob()
}
}
override fun onAdFailedToLoad(adError: LoadAdError) {
if (isDestroyed) return
adMobAd = null
nga.onMediationLoadFailed()
adMobRetry++
val delayMs = 1000L * 2.0.pow(min(6, adMobRetry)).toLong()
handler.postDelayed({ loadAdMob() }, delayMs)
}
},
)
}
// Call at the moment your game would show an interstitial.
fun showInterstitial() {
val adMob = adMobAd
if (adMob != null) {
pauseGame()
adMob.show(this) // the mediation always comes first
} else if (!nga.tryShow(this, ::pauseGame, ::afterNga)) {
continueGame() // AdMob has no fill and NGA has nothing ready
}
}
private fun afterAdMob() {
adMobAd = null
loadAdMob()
resumeGame()
continueGame()
}
private fun afterNga() {
if (isDestroyed) return
resumeGame()
continueGame()
}
// Your game's own code.
private fun pauseGame() {}
private fun resumeGame() {}
private fun continueGame() {}
companion object {
const val ADMOB_AD_UNIT = "YOUR_ADMOB_INTERSTITIAL_AD_UNIT"
}
}
iOS (Swift)
import UIKit
import GoogleMobileAds
// Google Mobile Ads is initialized, as Google's documentation says, before this screen opens.
final class AdMobBackfillViewController: UIViewController, FullScreenContentDelegate {
private static let adMobAdUnit = "YOUR_ADMOB_INTERSTITIAL_AD_UNIT"
private let nga = InterstitialBackfill() // InterstitialBackfill.swift, below
private var adMobAd: InterstitialAd?
private var adMobRetry = 0.0
override func viewDidLoad() {
super.viewDidLoad()
loadAdMob()
}
private func loadAdMob() {
Task { [weak self] in
do {
let ad = try await InterstitialAd.load(with: Self.adMobAdUnit, request: Request())
self?.adMobLoaded(ad)
} catch {
self?.adMobFailed()
}
}
}
private func adMobLoaded(_ ad: InterstitialAd) {
adMobAd = ad
nga.onMediationLoaded()
adMobRetry = 0
ad.fullScreenContentDelegate = self
}
private func adMobFailed() {
adMobAd = nil
nga.onMediationLoadFailed()
adMobRetry += 1
let delay = pow(2.0, min(6.0, adMobRetry))
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in self?.loadAdMob() }
}
// Call at the moment your game would show an interstitial.
func showInterstitial() {
if let adMob = adMobAd {
pauseGame()
adMob.present(from: self) // the mediation always comes first
} else if !nga.tryShow(from: self, pauseGame: pauseGame, afterAd: afterNga) {
continueGame() // AdMob has no fill and NGA has nothing ready
}
}
// FullScreenContentDelegate
func adDidDismissFullScreenContent(_ ad: FullScreenPresentingAd) { afterAdMob() }
func ad(_ ad: FullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) { afterAdMob() }
func ad(_ ad: FullScreenPresentingAd, didRecordPaidEventWith value: AdValue) {
AdMobRevenue.log(value, for: ad) // AdMob's revenue for NGA's reports: see Revenue and purchases
}
private func afterAdMob() {
adMobAd = nil
loadAdMob()
resumeGame()
continueGame()
}
private func afterNga() {
resumeGame()
continueGame()
}
// Your game's own code.
private func pauseGame() {}
private func resumeGame() {}
private func continueGame() {}
}
The helper #
InterstitialBackfill holds NGA's half for one screen: the load from the mediation's failure, the show when the mediation has nothing ready, and the resume when the show ends. The rewarded helper below has the same shape.
Unity (C#)
using System;
using NGA;
// NGA's interstitial backfill for one screen. Call OnMediationLoaded and OnMediationLoadFailed from your mediation's
// interstitial load callbacks, and TryShow at the show moment when the mediation's ad is not ready.
public sealed class InterstitialBackfill : NGAAdLoadCallback, NGAAdShowListener
{
const string NgaInterstitial = "plc_example_interstitial";
NGAAd backfill;
bool mediationNoFill; // the mediation's latest load failed
Action afterAd;
public void OnMediationLoaded() { mediationNoFill = false; }
public void OnMediationLoadFailed()
{
mediationNoFill = true;
if (backfill == null || !backfill.IsReady()) NGASDK.LoadAd(NgaInterstitial, this);
}
// Shows NGA's ad if the mediation's latest load failed and NGA's ad is ready: pauseGame first, afterAd when the
// show ends. Returns false, and calls nothing, when there is nothing to show.
public bool TryShow(Action pauseGame, Action afterAd)
{
if (!mediationNoFill || backfill == null || !backfill.IsReady()) return false;
pauseGame();
this.afterAd = afterAd;
backfill.Show(this); // the mediation has no fill: NGA fills the moment
return true;
}
// NGAAdLoadCallback
public void OnLoaded(NGAAd ad) { backfill = ad; }
public void OnFailed(string placementId, NGAError error) { } // the next mediation failure asks again
public void OnExpired(NGAAd ad) { if (backfill != null && backfill.OpportunityId == ad.OpportunityId) backfill = null; }
// NGAAdShowListener
public void OnShowStarted(NGAAd ad) { } // the impression counted
public void OnClicked(NGAAd ad) { }
public void OnRewardResult(NGAAd ad, NGARewardResult result) { } // interstitial: never called
public void OnCompleted(NGAAd ad, NGAShowCompletion completion) { }
public void OnClosed(NGAAd ad) { backfill = null; Finish(); }
public void OnShowFailed(NGAAd ad, NGAError error)
{
if (error.Code == NGAErrorCode.AlreadyShowing) return; // an NGA ad is still on screen; OnClosed follows
if (!ad.IsReady()) backfill = null;
Finish();
}
void Finish()
{
var done = afterAd;
afterAd = null;
done?.Invoke();
}
}
Android (Kotlin)
import android.app.Activity
import network.nga.sdk.NGAAd
import network.nga.sdk.NGAAdLoadCallback
import network.nga.sdk.NGAAdShowListener
import network.nga.sdk.NGAError
import network.nga.sdk.NGAErrorCode
import network.nga.sdk.NGASDK
import network.nga.sdk.NGAShowCompletion
// NGA's interstitial backfill for one screen. Call onMediationLoaded and onMediationLoadFailed from your mediation's
// interstitial load callbacks, and tryShow at the show moment when the mediation's ad is not ready.
class InterstitialBackfill : NGAAdLoadCallback, NGAAdShowListener {
private var backfill: NGAAd? = null
private var mediationNoFill = false // the mediation's latest load failed
private var afterAd: (() -> Unit)? = null
fun onMediationLoaded() {
mediationNoFill = false
}
fun onMediationLoadFailed() {
mediationNoFill = true
if (backfill?.isReady() != true) NGASDK.loadAd(NGA_INTERSTITIAL, this)
}
// Shows NGA's ad if the mediation's latest load failed and NGA's ad is ready: pauseGame first, afterAd when the
// show ends. Returns false, and calls nothing, when there is nothing to show.
fun tryShow(activity: Activity, pauseGame: () -> Unit, afterAd: () -> Unit): Boolean {
val ad = backfill?.takeIf { mediationNoFill && it.isReady() } ?: return false
pauseGame()
this.afterAd = afterAd
ad.show(activity, this) // the mediation has no fill: NGA fills the moment
return true
}
// NGAAdLoadCallback
override fun onLoaded(ad: NGAAd) {
backfill = ad
}
override fun onFailed(placementId: String, error: NGAError) {} // the next mediation failure asks again
override fun onExpired(ad: NGAAd) {
if (backfill === ad) backfill = null
}
// NGAAdShowListener
override fun onShowStarted(ad: NGAAd) {} // the impression counted
override fun onCompleted(ad: NGAAd, completion: NGAShowCompletion) {}
override fun onClosed(ad: NGAAd) {
if (backfill === ad) backfill = null
finish()
}
override fun onShowFailed(ad: NGAAd, error: NGAError) {
if (error.code == NGAErrorCode.ALREADY_SHOWING) return // an NGA ad is still on screen; onClosed follows
if (backfill === ad && !ad.isReady()) backfill = null
finish()
}
private fun finish() {
val done = afterAd
afterAd = null
done?.invoke()
}
companion object {
const val NGA_INTERSTITIAL = "plc_example_interstitial"
}
}
iOS (Swift)
import UIKit
import NGASDK
// NGA's interstitial backfill for one screen. Call onMediationLoaded and onMediationLoadFailed from your mediation's
// interstitial load callbacks, and tryShow at the show moment when the mediation's ad is not ready.
final class InterstitialBackfill: NSObject, NGAAdLoadCallback, NGAAdShowListener {
private static let ngaInterstitial = "plc_example_interstitial"
private var backfill: NGAAd?
private var mediationNoFill = false // the mediation's latest load failed
private var afterAd: (() -> Void)?
func onMediationLoaded() { mediationNoFill = false }
func onMediationLoadFailed() {
mediationNoFill = true
if backfill?.isReady != true { NGASDK.loadAd(Self.ngaInterstitial, callback: self) }
}
// Shows NGA's ad if the mediation's latest load failed and NGA's ad is ready: pauseGame first, afterAd when the
// show ends. Returns false, and calls nothing, when there is nothing to show.
func tryShow(from viewController: UIViewController, pauseGame: () -> Void, afterAd: @escaping () -> Void) -> Bool {
guard mediationNoFill, let ad = backfill, ad.isReady else { return false }
pauseGame()
self.afterAd = afterAd
ad.show(from: viewController, listener: self) // the mediation has no fill: NGA fills the moment
return true
}
// NGAAdLoadCallback
func onLoaded(_ ad: NGAAd) { backfill = ad }
func onFailed(placementId: String, error: NGAError) {} // the next mediation failure asks again
func onExpired(_ ad: NGAAd) {
if backfill === ad { backfill = nil }
}
// NGAAdShowListener
func onShowStarted(_ ad: NGAAd) {} // the impression counted
func onCompleted(_ ad: NGAAd, completion: NGAShowCompletion) {}
func onClosed(_ ad: NGAAd) {
if backfill === ad { backfill = nil }
finish()
}
func onShowFailed(_ ad: NGAAd, error: NGAError) {
if error.code == .alreadyShowing { return } // an NGA ad is still on screen; onClosed follows
if backfill === ad, !ad.isReady { backfill = nil }
finish()
}
private func finish() {
let done = afterAd
afterAd = nil
done?()
}
}
Rewarded #
Rewarded follows the rule, with your mediation's rewarded ad in place of its interstitial. Only the reward is different:
- NGA decides only whether the reward was earned; what it is stays with your game. Pay your own reward for that placement when
onRewardResultsaysgranted. - The reward is earned on the device as soon as the ad has been on screen long enough, even mid-ad. The ad then shows it as earned.
- A denial says why:
SKIPPED(the player closed the ad before earning it),INTERRUPTED(the ad stopped, for example the renderer crashed), orREJECTED(this ad grants no reward). Tell the player. - Every rewarded show that counts an impression gets exactly one
onRewardResult, beforeonCompletedandonClosed. A show that ends before its impression gets none. - Pay each
opportunityIdonce. It is unique to each ad. - If the game is killed mid-ad,
onAdClosedAfterRestarton yourNGAListeneris called at the next launch with the result. WhenrewardGrantedis true, call the example's pay-once method there:RewardedBackfill.PayOnce(C#),RewardedBackfill.payOnce(Kotlin), orpayOnceon yourRewardedBackfillinstance (Swift). - A reward that only makes sense in the moment (a revive, a continue) needs a rule for that restart: pay it if the moment is still there, else convert or drop it. NGA reports only that it was earned.
- Keep the paid ids where your game keeps its save data (
PlayerPrefs,SharedPreferences,UserDefaultsor your server), so a restart cannot pay twice. The examples keep them in memory for brevity.
Wire OnMediationLoaded and OnMediationLoadFailed to your mediation's rewarded ad (Rewarded ad to wire, in Your mediation) as the interstitial examples wire its interstitial. At the moment the player asks for a reward, show your mediation's rewarded ad if it is ready, and otherwise call TryShow / tryShow.
Unity (C#)
using System.Collections.Generic;
using UnityEngine;
using NGA;
// NGA's rewarded backfill. Call OnMediationLoaded and OnMediationLoadFailed from your mediation's
// rewarded-ad load callbacks, as the interstitial examples above do.
public class RewardedBackfill : MonoBehaviour, NGAAdLoadCallback, NGAAdShowListener
{
const string NgaRewarded = "plc_example_rewarded";
// Opportunity ids already paid. Keep them in your save data, so a restart cannot pay twice.
static readonly HashSet<string> paid = new HashSet<string>();
NGAAd backfill;
bool mediationNoFill;
public void OnMediationLoaded() { mediationNoFill = false; }
public void OnMediationLoadFailed()
{
mediationNoFill = true;
if (backfill == null || !backfill.IsReady()) NGASDK.LoadAd(NgaRewarded, this);
}
// At the moment the player asks for a reward and your mediation's rewarded ad is not ready.
public bool TryShow()
{
if (!mediationNoFill || backfill == null || !backfill.IsReady()) return false;
PauseGame();
backfill.Show(this);
return true;
}
// Also call this from NGAListener.OnAdClosedAfterRestart when rewardGranted is true.
public static void PayOnce(string opportunityId)
{
if (!paid.Add(opportunityId)) return;
// Give the player this placement's reward.
}
// NGAAdLoadCallback
public void OnLoaded(NGAAd ad) { if (this != null) backfill = ad; }
public void OnFailed(string placementId, NGAError error) { }
public void OnExpired(NGAAd ad) { if (backfill != null && backfill.OpportunityId == ad.OpportunityId) backfill = null; }
// NGAAdShowListener
public void OnShowStarted(NGAAd ad) { }
public void OnClicked(NGAAd ad) { }
public void OnRewardResult(NGAAd ad, NGARewardResult result)
{
if (result.Granted) PayOnce(ad.OpportunityId);
else Debug.Log($"No reward this time: {result.Denial}"); // Skipped, Rejected or Interrupted
}
public void OnCompleted(NGAAd ad, NGAShowCompletion completion) { }
public void OnClosed(NGAAd ad) { backfill = null; ResumeGame(); }
public void OnShowFailed(NGAAd ad, NGAError error)
{
if (error.Code == NGAErrorCode.AlreadyShowing) return;
if (!ad.IsReady()) backfill = null;
ResumeGame();
}
// Your game's own code.
void PauseGame() { }
void ResumeGame() { }
}
Android (Kotlin)
import android.app.Activity
import network.nga.sdk.NGAAd
import network.nga.sdk.NGAAdLoadCallback
import network.nga.sdk.NGAAdShowListener
import network.nga.sdk.NGAError
import network.nga.sdk.NGAErrorCode
import network.nga.sdk.NGARewardResult
import network.nga.sdk.NGASDK
import network.nga.sdk.NGAShowCompletion
// NGA's rewarded backfill, app-wide. Call onMediationLoaded and onMediationLoadFailed from your
// mediation's rewarded-ad load callbacks, as the interstitial examples above do.
object RewardedBackfill : NGAAdLoadCallback, NGAAdShowListener {
private const val NGA_REWARDED = "plc_example_rewarded"
// Opportunity ids already paid. Keep them in your save data, so a restart cannot pay twice.
private val paid = mutableSetOf<String>()
private var backfill: NGAAd? = null
private var mediationNoFill = false
private var onDone: (() -> Unit)? = null
fun onMediationLoaded() {
mediationNoFill = false
}
fun onMediationLoadFailed() {
mediationNoFill = true
if (backfill?.isReady() != true) NGASDK.loadAd(NGA_REWARDED, this)
}
// At the moment the player asks for a reward and your mediation's rewarded ad is not ready.
fun tryShow(activity: Activity, pauseGame: () -> Unit, resumeGame: () -> Unit): Boolean {
val ad = backfill?.takeIf { mediationNoFill && it.isReady() } ?: return false
pauseGame()
onDone = resumeGame
ad.show(activity, this)
return true
}
// Also call this from NGAListener.onAdClosedAfterRestart when rewardGranted is true.
fun payOnce(opportunityId: String) {
if (!paid.add(opportunityId)) return
// Give the player this placement's reward.
}
// NGAAdLoadCallback
override fun onLoaded(ad: NGAAd) {
backfill = ad
}
override fun onFailed(placementId: String, error: NGAError) {}
override fun onExpired(ad: NGAAd) {
if (backfill === ad) backfill = null
}
// NGAAdShowListener
override fun onShowStarted(ad: NGAAd) {}
override fun onRewardResult(ad: NGAAd, result: NGARewardResult) {
if (result.granted) payOnce(ad.opportunityId)
// else result.denial is SKIPPED, REJECTED or INTERRUPTED: tell the player
}
override fun onCompleted(ad: NGAAd, completion: NGAShowCompletion) {}
override fun onClosed(ad: NGAAd) {
if (backfill === ad) backfill = null
finish()
}
override fun onShowFailed(ad: NGAAd, error: NGAError) {
if (error.code == NGAErrorCode.ALREADY_SHOWING) return
if (backfill === ad && !ad.isReady()) backfill = null
finish()
}
private fun finish() {
onDone?.invoke()
onDone = null
}
}
iOS (Swift)
import UIKit
import NGASDK
// NGA's rewarded backfill. Keep one instance for the app, for example on your game controller, and call
// onMediationLoaded and onMediationLoadFailed from your mediation's rewarded-ad load callbacks, as the
// interstitial examples above do.
final class RewardedBackfill: NSObject, NGAAdLoadCallback, NGAAdShowListener {
private static let ngaRewarded = "plc_example_rewarded"
// Opportunity ids already paid. Keep them in your save data, so a restart cannot pay twice.
private var paid = Set<String>()
private var backfill: NGAAd?
private var mediationNoFill = false
private var onDone: (() -> Void)?
func onMediationLoaded() { mediationNoFill = false }
func onMediationLoadFailed() {
mediationNoFill = true
if backfill?.isReady != true { NGASDK.loadAd(Self.ngaRewarded, callback: self) }
}
// At the moment the player asks for a reward and your mediation's rewarded ad is not ready.
func tryShow(from viewController: UIViewController, pauseGame: () -> Void, resumeGame: @escaping () -> Void) -> Bool {
guard mediationNoFill, let ad = backfill, ad.isReady else { return false }
pauseGame()
onDone = resumeGame
ad.show(from: viewController, listener: self)
return true
}
// Also call this from NGAListener.onAdClosedAfterRestart when rewardGranted is true.
func payOnce(_ opportunityId: String) {
guard paid.insert(opportunityId).inserted else { return }
// Give the player this placement's reward.
}
// NGAAdLoadCallback
func onLoaded(_ ad: NGAAd) { backfill = ad }
func onFailed(placementId: String, error: NGAError) {}
func onExpired(_ ad: NGAAd) {
if backfill === ad { backfill = nil }
}
// NGAAdShowListener
func onShowStarted(_ ad: NGAAd) {}
func onRewardResult(_ ad: NGAAd, result: NGARewardResult) {
if result.granted { payOnce(ad.opportunityId) }
// else result.denial is .skipped, .rejected or .interrupted: tell the player
}
func onCompleted(_ ad: NGAAd, completion: NGAShowCompletion) {}
func onClosed(_ ad: NGAAd) {
if backfill === ad { backfill = nil }
finish()
}
func onShowFailed(_ ad: NGAAd, error: NGAError) {
if error.code == .alreadyShowing { return }
if backfill === ad, !ad.isReady { backfill = nil }
finish()
}
private func finish() {
onDone?()
onDone = nil
}
}
One ad per placement #
- One ad per placement at a time. Loading a placement that already has a ready ad gives you the same ad again; there is never a second ready ad for one placement. A game that needs two at once uses two placements.
- One NGA placement can back two of your mediation's ad units (two rewarded ad units, say). They share its one live ad, its caps and its row in the report. For separate caps or reporting, create one placement each.
- One full-screen ad at a time, app-wide. A
showwhile another NGA full-screen ad is on screen fails withALREADY_SHOWING, and the ad stays ready. - A refused show keeps the ad ready for your next moment:
ACTIVITY_NOT_RESUMED(the screen is not in front) and, on Android,RENDER_NOT_AVAILABLE / webview.unavailable. See AfteronShowFailed. - A loaded ad can be shown for 30 minutes. Then it expires, and the next mediation failure loads a new one. See
NGAAd.
The ad keeps running when the screen that called show is rotated or recreated: it runs in NGA's own screen. Its callbacks still go to the listener you passed to show, and a new screen can read the ad's state.
Next #
Read how attribution works, then test your integration.