Handle multiple ad requests

  • The IMA SDK for Android allows for managing multiple, concurrent ad requests by associating a unique context with each request.

  • Publishers can use the UserRequestContext field of an ad request to pass in a custom identifier (e.g., a Map).

  • This identifier can then be retrieved in the AdsManagerLoadedEvent or AdErrorEvent handlers using getUserRequestContext().

  • This functionality simplifies the process of differentiating between ad managers tied to specific video content or elements.

Select platform: HTML5 Android iOS tvOS

Most uses of the IMA SDK only require managing a single ad request at a time. However some edge case implementations, such as preloading ad data before the user selects a video, may require making multiple concurrent requests. Since ad requests are made asynchronously, ensuring the proper ad manager is associated with the correct context can seem to be a daunting task.

To simplify the process of differentiating multiple ad managers, the IMA SDK for Android allows publishers to pass in any value or object to the UserRequestContext field of any ad request. This value or object can then be retrieved in the AdsManagerLoadedEvent handler, by using the method getUserRequestContext().

Example

...

adsLoader = sdkFactory.createAdsLoader(context, imaSdkSettings, adDisplayContainer);

Map<String, String> userContextA = new HashMap<String, String>();
Map<String, String> userContextB = new HashMap<String, String>();
userContextA.put("id", "Request A");
userContextB.put("id", "Request B");
userContextA.put("element", "videoElementA");
userContextB.put("element", "videoElementB");
adRequestA.setUserRequestContext(userContextA);
adRequestB.setUserRequestContext(userContextB);

adsLoader.addAdsLoadedListener(
    new AdsLoader.AdsLoadedListener() {
      @Override
      public void onAdsManagerLoaded(AdsManagerLoadedEvent adsManagerLoadedEvent) {
        Map<String, String> context = adsManagerLoadedEvent.getUserRequestContext();
        adsManager = adsManagerLoadedEvent.getAdsManager();
        Log.i("ImaExample", "Successfully loaded ID: " + context.get("id"));
      }
    });

adsLoader.addAdErrorListener(
    new AdErrorEvent.AdErrorListener() {
      @Override
      public void onAdError(AdErrorEvent adErrorEvent) {
        Map<String, String> context = adErrorEvent.getUserRequestContext();
        Log.i("ImaExample", "Error with AdRequest. ID: " + context.get("id"));
        Log.i("ImaExample", "Ad Error: " + adErrorEvent.getError().getMessage());
      }
    });

adsLoader.requestAds(adRequestA);
adsLoader.requestAds(adRequestB);

...