Handle callbacks from background thread

This page covers the instructions to handle callbacks from a background thread.

The Next Gen Mobile Ads SDK runs ad load and event callbacks on a background thread. When performing UI-related operations within these callbacks, ensure you explicitly dispatch them to the UI thread.

The following examples add a banner view to view hierarchy after an ad loads:

Kotlin

BannerAd.load(
  adRequest,
  object : AdLoadCallback<BannerAd> {
    override fun onAdLoaded(ad: BannerAd) {
      // Add the banner view to the view hierarchy on the UI thread.
      activity?.runOnUiThread {
        binding.bannerViewContainer.addView(ad.getView(requireActivity()))
      }
    }
  },
)

Java

BannerAd.load(
    adRequest,
    new AdLoadCallback<BannerAd>() {
      @Override
      public void onAdLoaded(@NonNull BannerAd ad) {
        // Add the banner view to the view hierarchy on the UI thread.
        runOnUiThread(
            () -> binding.bannerViewContainer.addView(ad.getView(MainActivity.this)));
      }
    });