Xử lý nhiều yêu cầu quảng cáo bằng UserContext

Hầu hết các trường hợp sử dụng SDK IMA chỉ yêu cầu quản lý một yêu cầu quảng cáo tại một thời điểm. Tuy nhiên, một số phương pháp triển khai yêu cầu đặc biệt (chẳng hạn như tải trước dữ liệu quảng cáo trước khi người dùng chọn video) có thể đòi hỏi việc thực hiện nhiều yêu cầu đồng thời. Vì yêu cầu quảng cáo được thực hiện không đồng bộ, việc đảm bảo liên kết đúng trình quản lý quảng cáo với ngữ cảnh chính xác có thể là một tác vụ khó khăn.

Để đơn giản hoá quá trình phân biệt nhiều trình quản lý quảng cáo, SDK IMA dành cho Android cho phép nhà xuất bản chuyển bất kỳ giá trị hoặc đối tượng nào vào trường UserRequestContext của bất kỳ yêu cầu quảng cáo nào. Sau đó, bạn có thể truy xuất giá trị hoặc đối tượng này trong trình xử lý AdsManagerLoadedEvent bằng cách sử dụng phương thức getUserRequestContext().

Ví dụ:

...

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

...