Используйте собственные форматы нативной рекламы.

In addition to the system-defined native formats, Ad Manager publishers have the option of creating their own native ad formats by defining custom lists of assets. These are called custom native ad formats , and can be used with reserved ads. This enables publishers to pass arbitrary structured data to their apps. These ads are represented by the NativeCustomFormatAd object.

Загрузка пользовательских форматов нативной рекламы

В этом руководстве объясняется, как загружать и отображать пользовательские форматы нативной рекламы .

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

Чтобы загрузить пользовательскую нативную рекламу, выполните следующие действия:

  1. Включите тип объявления NativeAdType.CUSTOM_NATIVE в запрос NativeAdRequest .

  2. Укажите идентификатор формата пользовательской нативной рекламы.

Котлин

val adRequest =
  NativeAdRequest.Builder("AD_UNIT_ID", listOf(NativeAdType.CUSTOM_NATIVE))
    .setCustomFormatIds(listOf("CUSTOM_NATIVE_FORMAT_ID"))
    .build()

// Load the native ad with the ad request and callback.
NativeAdLoader.load(
  adRequest,
  object : NativeAdLoaderCallback {
    override fun onCustomNativeAdLoaded(customNativeAd: CustomNativeAd) {
      // TODO: Store the custom native ad.
    }

    override fun onAdFailedToLoad(adError: LoadAdError) {}
  },
)

Java

NativeAdRequest adRequest =
    new NativeAdRequest.Builder("AD_UNIT_ID", List.of(NativeAd.NativeAdType.CUSTOM_NATIVE))
        .setCustomFormatIds(Arrays.asList("CUSTOM_NATIVE_FORMAT_ID"))
        .build();

// Load the native ad with the ad request and callback.
NativeAdLoader.load(
    adRequest,
    new NativeAdLoaderCallback() {
      @Override
      public void onCustomNativeAdLoaded(@NonNull CustomNativeAd customNativeAd) {
        // TODO: Store the custom native ad.
      }

      @Override
      public void onAdFailedToLoad(@NonNull LoadAdError adError) {}
    });

Идентификатор пользовательского формата нативной рекламы

Идентификатор формата, используемый для идентификации пользовательского формата нативной рекламы, можно найти в пользовательском интерфейсе Ad Manager в разделе « Нативная реклама» в раскрывающемся списке «Доставка» :

Идентификатор каждого пользовательского формата нативной рекламы отображается рядом с его названием. Щелчок по одному из названий переводит вас на экран с подробной информацией о полях формата:

From here, individual fields can be added, edited, and removed. Note the Name of each of the assets. The name is the key used to get the data for each asset when displaying your custom native ad format.

Отображение пользовательских форматов нативной рекламы

Custom native ad formats differ from system-defined ones in that publishers have the power to define their own list of assets that make up an ad. Therefore, the process for displaying one differs from system-defined formats in a few ways:

  1. Текстовые и графические ресурсы доступны через геттеры getText() и getImage() , которые принимают имя поля в качестве параметра.
  2. Поскольку для регистрации в Google нет специального класса ViewGroup , вам необходимо вручную регистрировать показы и клики.
  3. Если в рекламном объявлении отсутствует видеофайл, оно будет иметь пустое значение null media content).

В этом примере показано, как отобразить CustomNativeAd :

Котлин

private fun displayCustomNativeAd(customNativeAd: CustomNativeAd, context: Context) {
  // Render the text elements.

  // The `customNativeAdBinding` is the layout binding for the ad container that
  // contains all `CustomNativeAd` assets.
  customNativeAdBinding.headline.text = customNativeAd.getText("Headline")
  customNativeAdBinding.caption.text = customNativeAd.getText("Caption")

  // If the main asset is an image, render it with an ImageView.
  val imageView = ImageView(context)
  imageView.adjustViewBounds = true
  imageView.setImageDrawable(customNativeAd.getImage("MainImage")?.drawable)
  imageView.setOnClickListener { customNativeAd.performClick("MainImage") }
  customNativeAdBinding.mediaPlaceholder.addView(imageView)

  // Render the ad choices icon.
  renderAdChoices(customNativeAd)

  // Record an impression.
  customNativeAd.recordImpression()
}

Java

private void displayCustomNativeAd(CustomNativeAd customNativeAd, Context context) {
  // Render the text elements.

  // The `customNativeAdBinding` is the layout binding for the ad container that
  // contains all `CustomNativeAd` assets.
  if (customNativeAdBinding != null) {
    customNativeAdBinding.headline.setText(customNativeAd.getText("Headline"));
    customNativeAdBinding.caption.setText(customNativeAd.getText("Caption"));

    ImageView imageView = new ImageView(context);
    imageView.setAdjustViewBounds(true);
    imageView.setImageDrawable(customNativeAd.getImage("MainImage").getDrawable());
    imageView.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            customNativeAd.performClick("MainImage");
          }
        });
    customNativeAdBinding.mediaPlaceholder.addView(imageView);

    // Render the ad choices icon.
    renderAdChoices(customNativeAd);

    // Record an impression.
    customNativeAd.recordImpression();
  }
}

Нативный видеоролик для создания пользовательских форматов нативной рекламы.

При создании пользовательского формата у вас есть возможность указать, что этот формат подходит для видео.

In your app implementation, you can use CustomNativeAd.getMediaContent() to get the media content. Then call setMediaContent() to set the media content on your media view. If the ad has null media content, make alternate plans to show the ad without a video.

В следующем примере проверяется наличие видеоконтента в объявлении, и если видео недоступно, вместо него отображается изображение:

Котлин

private fun displayVideoCustomNativeAd(customNativeAd: CustomNativeAd, context: Context) {
  // Check whether the custom native ad has video content.
  val mediaContent = customNativeAd.mediaContent
  if (mediaContent != null && mediaContent.hasVideoContent) {
    // Render the media content in a MediaView.
    val mediaView = MediaView(context)
    mediaView.mediaContent = mediaContent
    customNativeAdBinding.mediaPlaceholder.addView(mediaView)
  } else {
    // Fall back to other assets defined on your custom native ad.
    val imageView = ImageView(context)
    imageView.adjustViewBounds = true
    imageView.setImageDrawable(customNativeAd.getImage("MainImage")?.drawable)
    customNativeAdBinding.mediaPlaceholder.addView(imageView)
  }

  // Record an impression.
  customNativeAd.recordImpression()
}

Java

private void displayVideoCustomNativeAd(CustomNativeAd customNativeAd, Context context) {
  // Check whether the custom native ad has video content.
  MediaContent mediaContent = customNativeAd.getMediaContent();
  if (mediaContent != null && mediaContent.getHasVideoContent()) {
    // Render the media content in a MediaView.
    MediaView mediaView = new MediaView(context);
    mediaView.setMediaContent(mediaContent);
    customNativeAdBinding.mediaPlaceholder.addView(mediaView);
  } else {
    // Fall back to other assets defined on your custom native ad.
    ImageView imageView = new ImageView(context);
    imageView.setAdjustViewBounds(true);
    imageView.setImageDrawable(customNativeAd.getImage("MainImage").getDrawable());
    customNativeAdBinding.mediaPlaceholder.addView(imageView);
  }

  // Record an impression.
  customNativeAd.recordImpression();
}

Дополнительную информацию о том, как настроить видеоконтент в пользовательской нативной рекламе, см. в разделе «Видеореклама» .

Отобразить значок AdChoices

В рамках поддержки Закона о цифровых услугах (DSA) для показа рекламных объявлений о бронировании в Европейской экономической зоне (ЕЭЗ) требуется значок AdChoices и ссылка на страницу Google «Об этом объявлении» . При внедрении пользовательских нативных объявлений вы несете ответственность за отображение значка AdChoices. Мы рекомендуем предпринять шаги для отображения и установки обработчика кликов для значка AdChoices при отображении основных рекламных материалов.

В следующем примере предполагается, что вы определили элемент <ImageView /> в иерархии представлений для размещения логотипа AdChoices.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
    <ImageView
        android:id="@+id/adChoices"
        android:layout_width="15dp"
        android:layout_height="15dp"
        android:adjustViewBounds="true"
        android:contentDescription="AdChoices icon." />
</LinearLayout>

В приведенных ниже примерах отображается иконка AdChoices и настраивается соответствующее поведение при клике.

Котлин

private fun renderAdChoices(customNativeAd: CustomNativeAd) {
  // Render the AdChoices image.
  val adChoiceAsset = customNativeAd.getImage(NativeAdAssetNames.ASSET_ADCHOICES_CONTAINER_VIEW)
  if (adChoiceAsset != null) {
    customNativeAdBinding.adchoices.setImageDrawable(adChoiceAsset.drawable)
    customNativeAdBinding.adchoices.visibility = View.VISIBLE
    customNativeAdBinding.adchoices.setOnClickListener {
      // Handle click. See the next section for more details.
      customNativeAd.performClick(NativeAdAssetNames.ASSET_ADCHOICES_CONTAINER_VIEW)
    }
  } else {
    customNativeAdBinding.adchoices.visibility = View.GONE
  }
}

Java

private void renderAdChoices(CustomNativeAd customNativeAd) {
  // Render the AdChoices image.
  Image adChoiceAsset =
      customNativeAd.getImage(NativeAdAssetNames.ASSET_ADCHOICES_CONTAINER_VIEW);
  if (adChoiceAsset != null) {
    if (customNativeAdBinding != null) {
      customNativeAdBinding.adchoices.setImageDrawable(adChoiceAsset.getDrawable());
      customNativeAdBinding.adchoices.setVisibility(View.VISIBLE);
      customNativeAdBinding.adchoices.setOnClickListener(
          new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              // Handle click.
              customNativeAd.performClick(NativeAdAssetNames.ASSET_ADCHOICES_CONTAINER_VIEW);
            }
          });
    }
  } else {
    if (customNativeAdBinding != null) {
      customNativeAdBinding.adchoices.setVisibility(View.GONE);
    }
  }
}

Записывайте показы и составляйте отчеты по кликам.

Ваше приложение отвечает за запись показов и передачу данных о кликах в GMA Next-Gen SDK .

Запись впечатлений

Чтобы зарегистрировать показ пользовательской нативной рекламы, вызовите метод recordImpression() этой рекламы:

Котлин

// Record an impression.
customNativeAd.recordImpression()

Java

// Record an impression.
customNativeAd.recordImpression();

Если ваше приложение случайно вызовет этот метод дважды для одной и той же рекламы, SDK автоматически предотвратит запись дублирующего показа для одного запроса.

Сообщить о кликах

To report to the SDK that a click has occurred on an asset view, call the ad's performClick() method. Provide the name of the asset that was clicked using the same string you defined in the Ad Manager UI.

Котлин

imageView.setOnClickListener { customNativeAd.performClick("MainImage") }

Java

imageView.setOnClickListener(
    new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        customNativeAd.performClick("MainImage");
      }
    });

Note that you don't need to call this method for every view associated with your ad. If you had another field called "Caption" that was meant to be displayed but not clicked or tapped on by the user, your app wouldn't need to call performClick for that asset's view.

Реагировать на пользовательские действия по клику

При клике на объявление в пользовательском формате SDK может предложить три варианта ответа, которые выполняются в указанном порядке:

  1. Вызовите обработчик OnCustomClickListener , если он был предоставлен.
  2. Для каждой из прямых ссылок в рекламе попытайтесь найти обработчик контента и запустите первый, который его обнаружит.
  3. Откройте браузер и перейдите по целевому URL-адресу объявления.

Для реализации пользовательского действия по клику предоставьте обработчик OnCustomClickListener :

Котлин

customNativeAd.onCustomClickListener =
  object : OnCustomClickListener {
    override fun onCustomClick(assetName: String) {
      // Perform your custom action.
    }
  }

Java

customNativeAd.setOnCustomClickListener(
    new OnCustomClickListener() {
      @Override
      public void onCustomClick(@NonNull String assetName) {
        // Perform your custom action.
      }
    });

На первый взгляд, существование пользовательских обработчиков кликов может показаться странным. В конце концов, ваше приложение только что сообщило SDK о произошедшем клике, так почему же SDK должен сообщать об этом приложению?

This flow of information is useful for a few reasons, but most importantly it allows the SDK to remain in control of the response to the click. It can automatically ping third-party tracking URLs that have been set for the creative, for example, and handle other tasks behind the scenes, without any additional code.