IMA SDK 的大部分用途只需一次管理一个广告请求即可。不过,某些极端情况的实现(例如在用户选择视频之前预加载广告数据)可能需要发出多个并发请求。由于广告请求是异步发出的,因此确保将正确的 Ad Manager 与正确的上下文相关联似乎是一项艰巨的任务。
为了简化区分多个广告管理器的过程,IMA SDK for Android 允许发布商向任意广告请求的 UserRequestContext 字段传递任何值或对象。然后,您便可使用 getUserRequestContext() 方法在 AdsManagerLoadedEvent 处理程序中检索此值或对象。
示例
...
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);
...