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);
...