透過 UserContext 處理多個廣告請求

大部分 IMA SDK 的使用都只需要一次管理一個廣告請求。然而,在某些極端案例中 (例如在使用者選取影片前預先載入廣告資料) 可能需要發出多個並行要求。由於廣告請求是非同步進行,因此確保適當的 Ad Manager 與正確的內容建立關聯並不容易。

為簡化區分多個廣告管理員的程序,Android 的 IMA SDK 可讓發布商將任何值或物件傳入任何廣告請求的 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);

...