Таргетинг

Выберите платформу: Android iOS Unity Flutter Android (Legacy)

В этом руководстве объясняется, как передать информацию о таргетинге в SDK Google Mobile Ads.

Для просмотра рабочего примера загрузите демонстрационное приложение Android API.

Скачать демо-версию API

Предварительное условие

Прежде чем продолжить, настройте Google Mobile Ads SDK (Legacy) .

RequestConfiguration

RequestConfiguration собирает информацию о таргетинге, применяемую глобально к каждому запросу объявления. Список доступных тегов таргетинга см. в документации RequestConfiguration.Builder .

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

Котлин

val requestConfiguration = MobileAds.getRequestConfiguration()
MobileAds.setRequestConfiguration(requestConfiguration)

Java

RequestConfiguration requestConfiguration = MobileAds.getRequestConfiguration();
MobileAds.setRequestConfiguration(requestConfiguration);

Чтобы гарантировать применение изменений конфигурации запроса ко всем запросам рекламы, настройте конфигурацию запроса перед инициализацией Google Mobile Ads SDK (Legacy) .

Установить возраст лечения

To help you manage your compliance with applicable privacy regulations related to children and teens, Google Mobile Ads SDK (Legacy) provides an age treatment setting. The age treatment setting lets you indicate whether Google Mobile Ads SDK (Legacy) should apply specific ad serving protections for children, teens, or an unspecified age.

Вы можете установить возрастные ограничения для лечения с помощью метода setAgeRestrictedTreatment() , используемого в API RequestConfiguration.Builder .

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

Котлин

val requestConfiguration =
  MobileAds.getRequestConfiguration()
    .toBuilder()
    // Indicate that ad requests should have child age treatment.
    .setAgeRestrictedTreatment(AgeRestrictedTreatment.CHILD)
    .build()
MobileAds.setRequestConfiguration(requestConfiguration)

Java

RequestConfiguration requestConfiguration =
    MobileAds.getRequestConfiguration().toBuilder()
        // Indicate that ad requests should have child age treatment.
        .setAgeRestrictedTreatment(AgeRestrictedTreatment.CHILD)
        .build();
MobileAds.setRequestConfiguration(requestConfiguration);

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

  • TEEN
  • UNSPECIFIED

When using the setting, Google Mobile Ads SDK (Legacy) includes a tfat parameter in ad requests. Consult your legal counsel to determine the applicable age treatment for your users based on your legal and regulatory obligations. For more information, see Tag an ad request for age treatment .

Переход от лечения TFCD и TFUA к лечению, ориентированному на возраст.

Параметр «Возрастная принадлежность» заменяет устаревшие параметры .setTagForChildDirectedTreatment() (TFCD) и .setTagForUnderAgeOfConsent() (TFUA).

В следующей таблице показаны параметры TFCD и TFUA, а также их эквиваленты для разных возрастных групп:

TFCD

TFCD омоложение
TAG_FOR_CHILD_DIRECTED_TREATMENT_TRUE AgeRestrictedTreatment.CHILD
TAG_FOR_CHILD_DIRECTED_TREATMENT_FALSE AgeRestrictedTreatment.UNSPECIFIED
TAG_FOR_CHILD_DIRECTED_TREATMENT_UNSPECIFIED AgeRestrictedTreatment.UNSPECIFIED
Значение не присвоено .setTagForChildDirectedTreatment() AgeRestrictedTreatment.UNSPECIFIED
Нет эквивалента AgeRestrictedTreatment.TEEN

TFUA

TFUA омоложение
TAG_FOR_UNDER_AGE_OF_CONSENT_TRUE AgeRestrictedTreatment.CHILD
TAG_FOR_UNDER_AGE_OF_CONSENT_FALSE AgeRestrictedTreatment.UNSPECIFIED
TAG_FOR_UNDER_AGE_OF_CONSENT_UNSPECIFIED AgeRestrictedTreatment.UNSPECIFIED
Значение не присвоено .setTagForUnderAgeOfConsent() AgeRestrictedTreatment.UNSPECIFIED
Нет эквивалента AgeRestrictedTreatment.TEEN

Понимание взаимодействия возрастных изменений в лечении с TFCD и TFUA

Если вы зададите параметры лечения в зависимости от возраста, а также параметры TFCD или TFUA, Google применит наиболее консервативный подход.

Лечение старения с помощью медиации

Если вы настраиваете обработку возрастных ограничений с помощью Google Mobile Ads SDK (Legacy) , адаптеры медиации пересылают сигнал обработки возрастных ограничений в сторонние SDK, используемые для медиации.

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

Название адаптера медиации Минимальная поддерживаемая версия
AppLovin 13.6.3.0
BidMachine 3.7.1.1
Биго 5.9.0.1
Chartboost 9.12.1.1
DTExchange (Fyber) 8.4.5.1
i-mobile 2.3.2.4
InMobi 11.3.0.1
IronSource 9.4.3.0
Монетизация Liftoff (Vungle) 7.7.4.2
LY (Линия) 3.1.1.1
майо 2.0.9.0
Мета (Фейсбук) 6.21.0.4
Минтеграл 17.1.61.1
Молоко 4.10.0.0
MyTarget 5.47.1.1
Пэнгл 8.1.0.3.1
PubMatic 5.1.2.2
Верве 3.9.0.0

обстановка, ориентированная на ребенка

For purposes of the Children's Online Privacy Protection Act (COPPA) , there is a setting called "tag for child-directed treatment". By setting this tag, you certify that this notification is accurate and you are authorized to act on behalf of the owner of the app. You understand that abuse of this setting may result in termination of your Google Account.

As an app developer, you can indicate whether you want Google to treat your content as child-directed when you make an ad request. If you indicate that you want Google to treat your content as child-directed, we take steps to disable IBA and remarketing ads on that ad request.

Вы можете применить настройку, ориентированную на дочерние элементы, с помощью setTagForChildDirectedTreatment() :

  • Call setTagForChildDirectedTreatment with TAG_FOR_CHILD_DIRECTED_TREATMENT_TRUE to indicate that you want your content treated as child-directed for purposes of COPPA. This prevents the transmission of the Android advertising identifier (AAID) .

  • Вызовите setTagForChildDirectedTreatment с TAG_FOR_CHILD_DIRECTED_TREATMENT_FALSE чтобы указать, что вы не хотите, чтобы ваш контент обрабатывался как предназначенный для детей в соответствии с законом COPPA.

  • Call setTagForChildDirectedTreatment with TAG_FOR_CHILD_DIRECTED_TREATMENT_UNSPECIFIED if you don't want to indicate how you would like your content treated with respect to COPPA in ad requests.

Следующий пример показывает, что вы хотите, чтобы ваш контент рассматривался как предназначенный для детей в соответствии с законом COPPA:

Котлин

val requestConfiguration =
  MobileAds.getRequestConfiguration()
    .toBuilder()
    .setTagForChildDirectedTreatment(RequestConfiguration.TAG_FOR_CHILD_DIRECTED_TREATMENT_TRUE)
    .build()
MobileAds.setRequestConfiguration(requestConfiguration)

Java

RequestConfiguration requestConfiguration =
    MobileAds.getRequestConfiguration().toBuilder()
        .setTagForChildDirectedTreatment(
            RequestConfiguration.TAG_FOR_CHILD_DIRECTED_TREATMENT_TRUE)
        .build();
MobileAds.setRequestConfiguration(requestConfiguration);

You can mark your ad requests to receive treatment for users in the European Economic Area (EEA) under the age of consent. This feature is designed to help facilitate compliance with the General Data Protection Regulation (GDPR) . You may have other legal obligations under GDPR. Review European Union guidance and consult with your own legal counsel. Google's tools are designed to facilitate compliance and don't relieve any particular publisher of its obligations under the law. Learn more about how the GDPR affects publishers .

When using this feature, a Tag For Users under the Age of Consent in Europe (TFUA) parameter is included in the ad request. This parameter disables personalized advertising, including remarketing, for all ad requests. It also disables requests to third-party ad vendors, such as ad measurement pixels and third-party ad servers.

Подобно настройкам, управляемым дочерними элементами, в RequestConfiguration.Builder есть метод для установки параметра TFUA: setTagForUnderAgeOfConsent() со следующими параметрами.

  • Call setTagForUnderAgeOfConsent() with TAG_FOR_UNDER_AGE_OF_CONSENT_TRUE to indicate that you want the ad request to receive treatment for users in the European Economic Area (EEA) under the age of consent. This also prevents the transmission of the Android advertising identifier (AAID) .

  • Call setTagForUnderAgeOfConsent() with TAG_FOR_UNDER_AGE_OF_CONSENT_FALSE to indicate that you want the ad request to not receive treatment for users in the European Economic Area (EEA) under the age of consent.

  • Call setTagForUnderAgeOfConsent() with TAG_FOR_UNDER_AGE_OF_CONSENT_UNSPECIFIED to indicate that you have not specified whether the ad request should receive treatment for users in the European Economic Area (EEA) under the age of consent.

Следующий пример показывает, что вы хотите включить TFUA в ваши рекламные запросы:

Котлин

val requestConfiguration =
  MobileAds.getRequestConfiguration()
    .toBuilder()
    .setTagForUnderAgeOfConsent(RequestConfiguration.TAG_FOR_UNDER_AGE_OF_CONSENT_TRUE)
    .build()
MobileAds.setRequestConfiguration(requestConfiguration)

Java

RequestConfiguration requestConfiguration =
    MobileAds.getRequestConfiguration().toBuilder()
        .setTagForUnderAgeOfConsent(RequestConfiguration.TAG_FOR_UNDER_AGE_OF_CONSENT_TRUE)
        .build();
MobileAds.setRequestConfiguration(requestConfiguration);

Не следует одновременно устанавливать значение true для параметров "Управление по дочерним процессам" и setTagForUnderAgeOfConsent() . В противном случае приоритет имеет параметр "Управление по дочерним процессам".

Фильтрация рекламного контента

To comply with Google Play's Inappropriate Ads Policy that includes associated offers within an ad, all ads and their associated offers shown within your app must be appropriate for the content rating of your app, even if the content by itself is otherwise compliant with Google Play's policies.

Tools like maximum ad content rating can help you have more control over the content of the ads shown to your users. You can set a maximum content rating to help compliance with platform policies.

Apps can set a maximum ad content rating for their ad requests using the setMaxAdContentRating method. AdMob ads returned when this is configured have a content rating at or lower than that level. The possible values for this network extra are based on digital content label classifications , and must be one of the following strings:

  • MAX_AD_CONTENT_RATING_G
  • MAX_AD_CONTENT_RATING_PG
  • MAX_AD_CONTENT_RATING_T
  • MAX_AD_CONTENT_RATING_MA

Следующий код настраивает объект RequestConfiguration , указывая, что возвращаемый рекламный контент должен соответствовать обозначению метки цифрового контента не выше G :

Котлин

val requestConfiguration =
  MobileAds.getRequestConfiguration()
    .toBuilder()
    .setMaxAdContentRating(RequestConfiguration.MAX_AD_CONTENT_RATING_G)
    .build()
MobileAds.setRequestConfiguration(requestConfiguration)

Java

RequestConfiguration requestConfiguration =
    MobileAds.getRequestConfiguration().toBuilder()
        .setMaxAdContentRating(RequestConfiguration.MAX_AD_CONTENT_RATING_G)
        .build();
MobileAds.setRequestConfiguration(requestConfiguration);

Узнайте больше о настройке максимального рейтинга контента для каждого запроса рекламы .

Обработка персональных данных издателя (бета-версия)

The Publisher Privacy Treatment (PPT) API is an optional tool that lets apps indicate whether to turn off ads personalization for all ad requests using the setPublisherPrivacyPersonalizationState() method. When using this feature, a publisher privacy treatment (PPT) parameter is included in all future ad requests for the remainder of the session.

По умолчанию запросы на показ рекламы в Google сопровождаются персонализированной рекламой. Следующий код отключает персонализацию рекламы для всех запросов:

Котлин

val requestConfiguration =
  MobileAds.getRequestConfiguration()
    .toBuilder()
    .setPublisherPrivacyPersonalizationState(
      RequestConfiguration.PublisherPrivacyPersonalizationState.DISABLED
    )
    .build()
MobileAds.setRequestConfiguration(requestConfiguration)

Java

RequestConfiguration requestConfiguration =
    MobileAds.getRequestConfiguration().toBuilder()
        .setPublisherPrivacyPersonalizationState(
            RequestConfiguration.PublisherPrivacyPersonalizationState.DISABLED)
        .build();
MobileAds.setRequestConfiguration(requestConfiguration);

Запрос на рекламу

Объект AdManagerAdRequest собирает информацию о таргетинге, которая будет отправлена ​​вместе с запросом на показ рекламы.

Добавить дополнительные сетевые функции

Дополнительные данные сети — это дополнительная информация, отправляемая вместе с запросом на показ рекламы и относящаяся к конкретному источнику рекламы.

Следующий фрагмент кода устанавливает дополнительный параметр key со значением collapsible и значением bottom для Google:

Котлин

val extras = Bundle()
extras.putString("collapsible", "bottom")
val adRequest =
  AdRequest.Builder().addNetworkExtrasBundle(AdMobAdapter::class.java, extras).build()
adView.loadAd(adRequest)

Java

Bundle extras = new Bundle();
extras.putString("collapsible", "bottom");
AdRequest adRequest =
    new AdRequest.Builder().addNetworkExtrasBundle(AdMobAdapter.class, extras).build();
adView.loadAd(adRequest);

Настраиваемый таргетинг

Вы можете передавать пользовательские пары ключ-значение для таргетирования кампаний Google Ad Manager (позиций). В следующем примере в запросе объявления передается пользовательская пара ключ-значение:

Котлин

// Example: Pass custom targeting "age=25".
val newRequest = AdManagerAdRequest.Builder().addCustomTargeting("age", "25").build()

Java

// Example: Pass custom targeting "age=25".
AdManagerAdRequest newRequest =
    new AdManagerAdRequest.Builder().addCustomTargeting("age", "25").build();

В качестве ключа можно передать несколько значений в виде списка строк. Например, чтобы нацелиться на людей в возрасте около двадцати пяти лет, а не только на 25-летних.

Котлин

.addCustomTargeting("age", listOf("24", "25", "26"))

Java

.addCustomTargeting("age", Arrays.asList("24", "25", "26"))

Ознакомьтесь с примером пользовательского таргетинга в Ad Manager, чтобы увидеть реализацию пользовательского таргетинга в демонстрационном приложении Android API.

Исключения из категорий

Добавить уровень исключения категорий на уровне слота к запросу можно с помощью метода addCategoryExclusion() :

Котлин

// Example: Exclude "automobile" and "boat" categories.
val newRequest =
  AdManagerAdRequest.Builder()
    .addCategoryExclusion("automobile")
    .addCategoryExclusion("boat")
    .build()

Java

// Example: Exclude "automobile" and "boat" categories.
AdManagerAdRequest newRequest =
    new AdManagerAdRequest.Builder()
        .addCategoryExclusion("automobile")
        .addCategoryExclusion("boat")
        .build();

Для демонстрации возможности исключения категорий из рекламных кампаний в демонстрационном приложении Android API ознакомьтесь с примером использования исключений по категориям в Ad Manager .

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

You can set a publisher provided identifier (PPID) for use in frequency capping, audience segmentation and targeting, sequential ad rotation, and other audience-based ad delivery controls across devices.

Вот пример установки PPID:

Котлин

val adRequest = AdManagerAdRequest.Builder().setPublisherProvidedId("AB123456789").build()

Java

AdManagerAdRequest adRequest =
    new AdManagerAdRequest.Builder().setPublisherProvidedId("AB123456789").build();

Ознакомьтесь с примером использования идентификаторов, предоставляемых издателем (PPID), в демонстрационном приложении Android API в Ad Manager .

Сигналы, предоставленные издателем

You can send audience and contextual data as publisher provided signals (PPS) in ad requests. With PPS, you can use your user data to improve programmatic monetization by communicating your audience characteristics to bidders in all transaction types , using standard taxonomies, without the need to share user identifiers. Your audience characteristics can include behavioral and interest-based data ( IAB Audience Taxonomy 1.1 ) and contextual data ( IAB Content Taxonomy 2.2 ).

Котлин

val extras = Bundle()
// Set the demographic to an audience with an "Age Range" of 30-34 and an
// interest in mergers and acquisitions.
extras.putIntegerArrayList("IAB_AUDIENCE_1_1", arrayListOf(6, 284))
// Set the content to sedan, station wagon and SUV automotive values.
extras.putIntegerArrayList("IAB_CONTENT_2_2", arrayListOf(4, 5, 6))

val request =
  AdManagerAdRequest.Builder().addNetworkExtrasBundle(AdMobAdapter::class.java, extras).build()

Java

Bundle extras = new Bundle();
// Set the demographic to an audience with an "Age Range" of 30-34 and an
// interest in mergers and acquisitions.
extras.putIntegerArrayList("IAB_AUDIENCE_1_1", new ArrayList<>(Arrays.asList(6, 284)));
// Set the content to sedan, station wagon and SUV automotive values.
extras.putIntegerArrayList("IAB_CONTENT_2_2", new ArrayList<>(Arrays.asList(4, 5, 6)));

AdManagerAdRequest request =
    new AdManagerAdRequest.Builder().addNetworkExtrasBundle(AdMobAdapter.class, extras).build();

URL содержимого

Для указания URL-адреса контента в целях целевой рекламы и обеспечения безопасности бренда добавьте следующее:

Котлин

val builder = AdManagerAdRequest.Builder()
builder.setContentUrl("https://www.example.com")
val request = builder.build()

Java

AdManagerAdRequest.Builder builder = new AdManagerAdRequest.Builder();
builder.setContentUrl("https://www.example.com");
AdManagerAdRequest request = builder.build();

Безопасность бренда (бета-версия)

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

Котлин

val urls =
  mutableListOf(
    "https://www.mycontenturl1.com",
    "https://www.mycontenturl2.com",
    "https://www.mycontenturl3.com",
    "https://www.mycontenturl4.com",
  )

val requestWithContent = AdManagerAdRequest.Builder().setNeighboringContentUrls(urls).build()

Java

List<String> urls =
    Arrays.asList(
        "https://www.mycontenturl1.com",
        "https://www.mycontenturl2.com",
        "https://www.mycontenturl3.com",
        "https://www.mycontenturl4.com");

AdManagerAdRequest requestWithContent =
    new AdManagerAdRequest.Builder().setNeighboringContentUrls(urls).build();

.setNeighboringContentUrls() отличается от .setContentUrl() тем, что используется исключительно для защиты бренда.