Пользовательские события баннерной рекламы

Выберите платформу: Android iOS Android (устаревшая версия)

Предварительные требования

Завершите настройку пользовательских событий .

Запросить баннерную рекламу

When the custom event line item is reached in the waterfall mediation chain, the loadBannerAd() method is called on the class name you provided when creating a custom event . In this case, that method is in SampleCustomEvent , which then calls the loadBannerAd() method in SampleBannerCustomEventLoader .

Для запроса баннерной рекламы создайте или измените класс, наследующий Adapter , чтобы он реализовывал loadBannerAd() . Кроме того, создайте новый класс, реализующий MediationBannerAd .

В нашем примере с пользовательским событием класс SampleCustomEvent наследует класс Adapter , а затем делегирует обработку классу SampleBannerCustomEventLoader .

Java

package com.google.ads.mediation.sample.customevent;

import com.google.android.gms.ads.mediation.Adapter;
import com.google.android.gms.ads.mediation.MediationAdConfiguration;
import com.google.android.gms.ads.mediation.MediationAdLoadCallback;
import com.google.android.gms.ads.mediation.MediationBannerAd;
import com.google.android.gms.ads.mediation.MediationBannerAdCallback;
...

public class SampleCustomEvent extends Adapter {
  private SampleBannerCustomEventLoader bannerLoader;
  @Override
  public void loadBannerAd(
      @NonNull MediationBannerAdConfiguration adConfiguration,
      @NonNull MediationAdLoadCallback<MediationBannerAd, MediationBannerAdCallback> callback) {
    bannerLoader = new SampleBannerCustomEventLoader(adConfiguration, callback);
    bannerLoader.loadAd();
  }
}

SampleBannerCustomEventLoader отвечает за выполнение следующих задач:

  • Загрузка баннерной рекламы и вызов метода MediationAdLoadCallback после завершения загрузки.

  • Реализация интерфейса MediationBannerAd .

  • Получение и передача обратных вызовов событий рекламы в Google Mobile Ads SDK (Legacy) .

Необязательный параметр, определенный в UI is included in the ad configuration. The parameter can be accessed through adConfiguration.getServerParameters().getString(MediationConfiguration.CUSTOM_EVENT_SERVER_PARAMETER_FIELD) . This parameter is typically an ad unit identifier that an ad network SDK requires when instantiating an ad object.

Java

package com.google.ads.mediation.sample.customevent;

import com.google.android.gms.ads.mediation.Adapter;
import com.google.android.gms.ads.mediation.MediationBannerAdConfiguration;
import com.google.android.gms.ads.mediation.MediationAdLoadCallback;
import com.google.android.gms.ads.mediation.MediationBannerAd;
import com.google.android.gms.ads.mediation.MediationBannerAdCallback;
...

public class SampleBannerCustomEventLoader extends SampleAdListener implements MediationBannerAd {

  /** View to contain the sample banner ad. */
  private SampleAdView sampleAdView;

  /** Configuration for requesting the banner ad from the third-party network. */
  private final MediationBannerAdConfiguration mediationBannerAdConfiguration;

  /** Callback that fires on loading success or failure. */
  private final MediationAdLoadCallback<MediationBannerAd, MediationBannerAdCallback>
      mediationAdLoadCallback;

  /** Callback for banner ad events. */
  private MediationBannerAdCallback bannerAdCallback;

  /** Constructor. */
  public SampleBannerCustomEventLoader(
      @NonNull MediationBannerAdConfiguration mediationBannerAdConfiguration,
      @NonNull MediationAdLoadCallback<MediationBannerAd, MediationBannerAdCallback>
              mediationAdLoadCallback) {
    this.mediationBannerAdConfiguration = mediationBannerAdConfiguration;
    this.mediationAdLoadCallback = mediationAdLoadCallback;
  }

  /** Loads a banner ad from the third-party ad network. */
  public void loadAd() {
    // All custom events have a server parameter named "parameter" that returns
    // back the parameter entered into the UI when defining the custom event.
    Log.i("BannerCustomEvent", "Begin loading banner ad.");
    String serverParameter =
        mediationBannerAdConfiguration.getServerParameters().getString(
        MediationConfiguration.CUSTOM_EVENT_SERVER_PARAMETER_FIELD);

    Log.d("BannerCustomEvent", "Received server parameter.");

    Context context = mediationBannerAdConfiguration.getContext();
    sampleAdView = new SampleAdView(context);

    // Assumes that the serverParameter is the ad unit of the Sample Network.
    sampleAdView.setAdUnit(serverParameter);
    AdSize size = mediationBannerAdConfiguration.getAdSize();

    // Internally, smart banners use constants to represent their ad size, which
    // means a call to AdSize.getHeight could return a negative value. You can
    // accommodate this by using AdSize.getHeightInPixels and
    // AdSize.getWidthInPixels instead, and then adjusting to match the device's
    // display metrics.
    int widthInPixels = size.getWidthInPixels(context);
    int heightInPixels = size.getHeightInPixels(context);
    DisplayMetrics displayMetrics = Resources.getSystem().getDisplayMetrics();
    int widthInDp = Math.round(widthInPixels / displayMetrics.density);
    int heightInDp = Math.round(heightInPixels / displayMetrics.density);

    sampleAdView.setSize(new SampleAdSize(widthInDp, heightInDp));
    sampleAdView.setAdListener(this);

    SampleAdRequest request = createSampleRequest(mediationBannerAdConfiguration);
    Log.i("BannerCustomEvent", "Start fetching banner ad.");
    sampleAdView.fetchAd(request);
  }

  public SampleAdRequest createSampleRequest(
      MediationAdConfiguration mediationAdConfiguration) {
    SampleAdRequest request = new SampleAdRequest();
    request.setTestMode(mediationAdConfiguration.isTestRequest());
    request.setKeywords(mediationAdConfiguration.getMediationExtras().keySet());
    return request;
  }
}

Depending on whether the ad is successfully fetched or encounters an error, you would call either onSuccess() or onFailure() . onSuccess() is called by passing in an instance of the class that implements MediationBannerAd .

Как правило, эти методы реализуются внутри коллбэков стороннего SDK, который использует ваш адаптер. В этом примере в Sample SDK есть SampleAdListener с соответствующими коллбэками:

Java

@Override
public void onAdFetchSucceeded() {
  bannerAdCallback = mediationAdLoadCallback.onSuccess(this);
}

@Override
public void onAdFetchFailed(SampleErrorCode errorCode) {
  mediationAdLoadCallback.onFailure(SampleCustomEventError.createSampleSdkError(errorCode));
}

Для работы MediationBannerAd необходимо реализовать метод-геттер View :

Java

@Override
@NonNull
public View getView() {
  return sampleAdView;
}

Пересылать события медиации в Google Mobile Ads SDK (Legacy)

Once onSuccess() is called, the returned MediationBannerAdCallback object can then be used by the adapter to forward presentation events from the third-party SDK to Google Mobile Ads SDK (Legacy) . The SampleBannerCustomEventLoader class extends the SampleAdListener interface to forward callbacks from the sample ad network to Google Mobile Ads SDK (Legacy) .

It's important that your custom event forwards as many of these callbacks as possible, so that your app receives these equivalent events from the Google Mobile Ads SDK. Here's an example of using callbacks:

Java

@Override
public void onAdFullScreen() {
  bannerAdCallback.onAdOpened();
  bannerAdCallback.reportAdClicked();
}

@Override
public void onAdClosed() {
  bannerAdCallback.onAdClosed();
}

This completes the custom events implementation for banner ads. The full example is available on GitHub . You can use it with an ad network that is already supported or modify it to display custom event banner ads.