Специальные события для рекламы с вознаграждением

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

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

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

Запросить рекламу с вознаграждением

When the custom event line item is reached in the waterfall mediation chain, the loadRewardedAd() 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 loadRewardedAd() method in SampleRewardedCustomEventLoader .

Чтобы запросить показ рекламы с вознаграждением, создайте или измените класс, наследующий Adapter , чтобы он реализовывал loadRewardedAd() . Кроме того, создайте новый класс, реализующий MediationRewardedAd .

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

Java

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

import com.google.android.gms.ads.mediation.Adapter;
import com.google.android.gms.ads.mediation.MediationRewardedAdConfiguration;
import com.google.android.gms.ads.mediation.MediationAdConfiguration;
import com.google.android.gms.ads.mediation.MediationAdLoadCallback;
import com.google.android.gms.ads.mediation.MediationRewardedAd;
import com.google.android.gms.ads.mediation.MediationRewardedAdCallback;
...

public class SampleCustomEvent extends Adapter {

  private SampleNativeCustomEventLoader nativeLoader;

  @Override
  public void loadRewardedAd(
      @NonNull MediationRewardedAdConfiguration mediationRewardedAdConfiguration,
      @NonNull
          MediationAdLoadCallback<MediationRewardedAd, MediationRewardedAdCallback>
              mediationAdLoadCallback) {
    rewardedLoader =
        new SampleRewardedCustomEventLoader(
            mediationRewardedAdConfiguration, mediationAdLoadCallback);
    rewardedLoader.loadAd();
  }
}

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

  • Загрузка рекламного объявления с вознаграждением.

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

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

The optional parameter defined in the Ad Manager 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.MediationRewardedAdConfiguration;
import com.google.android.gms.ads.mediation.MediationAdLoadCallback;
import com.google.android.gms.ads.mediation.MediationRewardedAd;
import com.google.android.gms.ads.mediation.MediationRewardedAdCallback;
...

public class SampleRewardedCustomEventLoader extends SampleRewardedAdListener
    implements MediationRewardedAd {

  /** Configuration for requesting the rewarded ad from the third-party network. */
  private final MediationRewardedAdConfiguration mediationRewardedAdConfiguration;

  /**
   * A {@link MediationAdLoadCallback} that handles any callback when a Sample
   * rewarded ad finishes loading.
   */
  private final MediationAdLoadCallback<MediationRewardedAd, MediationRewardedAdCallback>
      mediationAdLoadCallback;

  /** Callback for rewarded ad events. */
  private MediationRewardedAdCallback rewardedAdCallback;

  /** Constructor. */
  public SampleRewardedCustomEventLoader(
      @NonNull MediationRewardedAdConfiguration mediationRewardedAdConfiguration,
      @NonNull MediationAdLoadCallback<MediationRewardedAd, MediationRewardedAdCallback>
              mediationAdLoadCallback) {
    this.mediationRewardedAdConfiguration = mediationRewardedAdConfiguration;
    this.mediationAdLoadCallback = mediationAdLoadCallback;
  }

  /** Loads the rewarded 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 AdMob UI when defining the custom event.
    Log.i("RewardedCustomEvent", "Begin loading rewarded ad.");
    String serverParameter = mediationRewardedAdConfiguration
        .getServerParameters()
        .getString(MediationConfiguration
        .CUSTOM_EVENT_SERVER_PARAMETER_FIELD);
    Log.d("RewardedCustomEvent", "Received server parameter.");
    SampleAdRequest request = createSampleRequest(mediationRewardedAdConfiguration);
    sampleRewardedAd = new SampleRewardedAd(serverParameter);
    sampleRewardedAd.setListener(this);
    Log.i("RewardedCustomEvent", "Start fetching rewarded ad.");
    sampleRewardedAd.loadAd(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 MediationRewardedAd .

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

Java

@Override
public void onRewardedAdLoaded() {
  rewardedAdCallback = mediationAdLoadCallback.onSuccess(this);
}

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

Для отображения объявления MediationRewardedAd требуется реализовать метод showAd() :

Java

@Override
public void showAd(Context context) {
  if (!(context instanceof Activity)) {
    rewardedAdCallback.onAdFailedToShow(
        SampleCustomEventError.createCustomEventNoActivityContextError());
    return;
  }
  Activity activity = (Activity) context;

  if (!sampleRewardedAd.isAdAvailable()) {
    rewardedAdCallback.onAdFailedToShow(
        SampleCustomEventError.createCustomEventAdNotAvailableError());
    return;
  }
  sampleRewardedAd.showAd(activity);
}

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

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

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 (Legacy) . Here's an example of using callbacks:

Java

@Override
public void onAdRewarded(final String rewardType, final int amount) {
  RewardItem rewardItem =
      new RewardItem() {
        @Override
        public String getType() {
          return rewardType;
        }

        @Override
        public int getAmount() {
          return amount;
        }
      };
  rewardedAdCallback.onUserEarnedReward(rewardItem);
}

@Override
public void onAdClicked() {
  rewardedAdCallback.reportAdClicked();
}

@Override
public void onAdFullScreen() {
  rewardedAdCallback.onAdOpened();
  rewardedAdCallback.onVideoStart();
  rewardedAdCallback.reportAdImpression();
}

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

@Override
public void onAdCompleted() {
  rewardedAdCallback.onVideoComplete();
}

This completes the custom events implementation for rewarded 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 rewarded ads.