Показать нативное объявление

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

Когда загружается нативная реклама, Google Mobile Ads SDK (Legacy) вызывает обработчик для соответствующего формата рекламы. Затем ваше приложение отвечает за отображение рекламы, хотя это не обязательно должно происходить немедленно. Чтобы упростить отображение системно определенных форматов рекламы, SDK предлагает несколько полезных ресурсов, описанных ниже.

Определите класс NativeAdView

Определите класс NativeAdView . Этот класс является классом ViewGroup и представляет собой контейнер верхнего уровня для класса NativeAdView . Каждое представление нативной рекламы содержит нативные рекламные ресурсы, такие как элемент представления MediaView или элемент представления Title , которые должны быть дочерними элементами объекта NativeAdView .

XML-макет

Добавьте XML- NativeAdView в свой проект:

<com.google.android.gms.ads.nativead.NativeAdView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <LinearLayout
    android:orientation="vertical">
        <LinearLayout
        android:orientation="horizontal">
          <ImageView
          android:id="@+id/ad_app_icon" />
          <TextView
            android:id="@+id/ad_headline" />
        </LinearLayout>
        <!--Add remaining assets such as the image and media view.-->
    </LinearLayout>
</com.google.android.gms.ads.nativead.NativeAdView>

Композитор Jetpack

  1. Include the JetpackCompose Utilities folder. This folder includes helpers for composing the NativeAdView object and assets.

Создайте NativeAdView :

  import com.google.android.gms.compose_util.NativeAdAttribution
  import com.google.android.gms.compose_util.NativeAdView

  @Composable
  /** Display a native ad with a user defined template. */
  fun DisplayNativeAdView(nativeAd: NativeAd) {
      NativeAdView {
          // Display the ad attribution.
          NativeAdAttribution(text = context.getString("Ad"))
          // Add remaining assets such as the image and media view.
        }
    }

Обработка загруженной нативной рекламы

When a native ad loads, handle the callback event, inflate the native ad view, and add it to the view hierarchy:

Java

AdLoader.Builder builder = new AdLoader.Builder(this, "/21775744923/example/native")
    .forNativeAd(new NativeAd.OnNativeAdLoadedListener() {
        @Override
        public void onNativeAdLoaded(NativeAd nativeAd) {
            // Assumes you have a placeholder FrameLayout in your View layout
            // (with ID fl_adplaceholder) where the ad is to be placed.
            FrameLayout frameLayout =
                findViewById(R.id.fl_adplaceholder);
            // Assumes that your ad layout is in a file call native_ad_layout.xml
            // in the res/layout folder
            NativeAdView adView = (NativeAdView) getLayoutInflater()
                .inflate(R.layout.native_ad_layout, null);
            // This method sets the assets into the ad view.
            displayNativeAd(nativeAd, adView);
            frameLayout.removeAllViews();
            frameLayout.addView(adView);
        }
});

Котлин

val builder = AdLoader.Builder(this, "/21775744923/example/native")
    .forNativeAd { nativeAd ->
        // Assumes you have a placeholder FrameLayout in your View layout
        // (with ID fl_adplaceholder) where the ad is to be placed.
        val frameLayout: FrameLayout = findViewById(R.id.fl_adplaceholder)
        // Assumes that your ad layout is in a file call native_ad_layout.xml
        // in the res/layout folder
        val adView = layoutInflater
                .inflate(R.layout.native_ad_layout, null) as NativeAdView
        // This method sets the assets into the ad view.
        displayNativeAd(nativeAd, adView)
        frameLayout.removeAllViews()
        frameLayout.addView(adView)
    }

Композитор Jetpack

@Composable
/** Load and display a native ad. */
fun NativeScreen() {
  var nativeAd by remember { mutableStateOf<NativeAd?>(null) }
  val context = LocalContext.current
  var isDisposed by remember { mutableStateOf(false) }

  DisposableEffect(Unit) {
    // Load the native ad when we launch this screen
    loadNativeAd(
      context = context,
      onAdLoaded = { ad ->
        // Handle the native ad being loaded.
        if (!isDisposed) {
          nativeAd = ad
        } else {
          // Destroy the native ad if loaded after the screen is disposed.
          ad.destroy()
        }
      },
    )
    // Destroy the native ad to prevent memory leaks when we dispose of this screen.
    onDispose {
      isDisposed = true
      nativeAd?.destroy()
      nativeAd = null
    }
  }

  // Display the native ad view with a user defined template.
  nativeAd?.let { adValue -> DisplayNativeAdView(adValue) }
}

fun loadNativeAd(context: Context, onAdLoaded: (NativeAd) -> Unit) {
  val adLoader =
    AdLoader.Builder(context, NATIVE_AD_UNIT_ID)
      .forNativeAd { nativeAd -> onAdLoaded(nativeAd) }
      .withAdListener(
        object : AdListener() {
          override fun onAdFailedToLoad(error: LoadAdError) {
            Log.e(TAG, "Native ad failed to load: ${error.message}")
          }

          override fun onAdLoaded() {
            Log.d(TAG, "Native ad was loaded.")
          }

          override fun onAdImpression() {
            Log.d(TAG, "Native ad recorded an impression.")
          }

          override fun onAdClicked() {
            Log.d(TAG, "Native ad was clicked.")
          }
        }
      )
      .build()
  adLoader.loadAd(AdRequest.Builder().build())
}

Обратите внимание, что все ресурсы для данной нативной рекламы должны отображаться внутри макета NativeAdView . Google Mobile Ads SDK (Legacy) пытается вывести предупреждение, если нативные ресурсы отображаются вне макета представления нативной рекламы.

Классы представлений рекламы также предоставляют методы для регистрации представления, используемого для каждого отдельного ресурса, и метод для регистрации самого объекта NativeAd . Такая регистрация представлений позволяет SDK автоматически обрабатывать такие задачи, как:

  • Запись щелчков
  • Recording impressions when the first pixel is visible on the screen
  • Displaying the AdChoices overlay for native backfill creatives—currently limited to a select group of publishers

Показать нативную рекламу

The following example demonstrates how to display a native ad:

Java

private void displayNativeAd(ViewGroup parent, NativeAd ad) {

  // Inflate a layout and add it to the parent ViewGroup.
  LayoutInflater inflater = (LayoutInflater) parent.getContext()
          .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  NativeAdView adView = (NativeAdView) inflater
          .inflate(R.layout.ad_layout_file, parent);

  // Locate the view that will hold the headline, set its text, and call the
  // NativeAdView's setHeadlineView method to register it.
  TextView headlineView = adView.findViewById<TextView>(R.id.ad_headline);
  headlineView.setText(ad.getHeadline());
  adView.setHeadlineView(headlineView);

  // Repeat the process for the other assets in the NativeAd
  // using additional view objects (Buttons, ImageViews, etc).

  // If you use a MediaView, call theNativeAdView.setMediaView() method
  // before calling the NativeAdView.setNativeAd() method.
  MediaView mediaView = (MediaView) adView.findViewById(R.id.ad_media);
  adView.setMediaView(mediaView);

  // Register the native ad with its ad view.
  adView.setNativeAd(ad);

  // Ensure that the parent view doesn't already contain an ad view.
  parent.removeAllViews();

  // Place the AdView into the parent.
  parent.addView(adView);
}

Котлин

fun displayNativeAd(parent: ViewGroup, ad: NativeAd) {

  // Inflate a layout and add it to the parent ViewGroup.
  val inflater = parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)
          as LayoutInflater
  val adView = inflater.inflate(R.layout.ad_layout_file, parent) as NativeAdView

  // Locate the view that will hold the headline, set its text, and use the
  // NativeAdView's headlineView property to register it.
  val headlineView = adView.findViewById<TextView>(R.id.ad_headline)
  headlineView.text = ad.headline
  adView.headlineView = headlineView

  // Repeat the process for the other assets in the NativeAd using
  // additional view objects (Buttons, ImageViews, etc).

  val mediaView = adView.findViewById<MediaView>(R.id.ad_media)
  adView.mediaView = mediaView

  // Call the NativeAdView's setNativeAd method to register the
  // NativeAdObject.
  adView.setNativeAd(ad)

  // Ensure that the parent view doesn't already contain an ad view.
  parent.removeAllViews()

  // Place the AdView into the parent.
  parent.addView(adView)
}

Композитор Jetpack

@Composable
/** Display a native ad with a user defined template. */
fun DisplayNativeAdView(nativeAd: NativeAd) {
  Box(modifier = Modifier.padding(8.dp)) {
    // Call the NativeAdView composable to display the native ad.
    NativeAdView(nativeAd) {
      Column(modifier = Modifier.fillMaxWidth()) {
        Box {
          Row(modifier = Modifier.fillMaxWidth()) {
            // If available, display the icon asset.
            nativeAd.icon?.let { icon ->
              NativeAdIconView(Modifier.padding(5.dp)) {
                icon.drawable?.toBitmap()?.let { bitmap ->
                  Image(bitmap = bitmap.asImageBitmap(), "Icon")
                }
              }
            }
            Column {
              // If available, display the headline asset.
              nativeAd.headline?.let {
                NativeAdHeadlineView {
                  Text(text = it, style = MaterialTheme.typography.headlineLarge)
                }
              }
              // If available, display the star rating asset.
              nativeAd.starRating?.let {
                NativeAdStarRatingView {
                  Text(text = "Rated $it", style = MaterialTheme.typography.labelMedium)
                }
              }
            }
          }
          // Display the ad attribution.
          NativeAdAttribution(
            modifier = Modifier.align(Alignment.TopStart),
            text = stringResource(R.string.attribution),
          )
        }

        // Display the media asset.
        NativeAdMediaView(modifier = Modifier.fillMaxWidth())

        // If available, display the body asset.
        nativeAd.body?.let {
          NativeAdBodyView(modifier = Modifier.padding(5.dp)) { Text(text = it) }
        }

        Row(Modifier.align(Alignment.End).padding(5.dp)) {
          // If available, display the price asset.
          nativeAd.price?.let {
            NativeAdPriceView(Modifier.padding(5.dp).align(Alignment.CenterVertically)) {
              Text(text = it)
            }
          }
          // If available, display the store asset.
          nativeAd.store?.let {
            NativeAdStoreView(Modifier.padding(5.dp).align(Alignment.CenterVertically)) {
              Text(text = it)
            }
          }
          // If available, display the call to action asset.
          nativeAd.callToAction?.let { callToAction ->
            NativeAdCallToActionView(Modifier.padding(5.dp)) { NativeAdButton(text = callToAction) }
          }
        }
      }
    }
  }
}

Наложение AdChoices

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

Атрибуция рекламы для программной нативной рекламы

When displaying programmatic native ads, you must display an ad attribution to denote that the view is an advertisement. Learn more in our policy guidelines .

Обработка кликов

Не следует реализовывать собственные обработчики кликов для каких-либо представлений поверх или внутри нативного рекламного представления. Клики по ресурсам рекламного представления обрабатываются SDK при условии правильного заполнения и регистрации этих ресурсов.

To listen for clicks, implement Google Mobile Ads SDK (Legacy) click callback:

Java

AdLoader adLoader = new AdLoader.Builder(context, "/21775744923/example/native")
    // ...
    .withAdListener(new AdListener() {
        @Override
        public void onAdFailedToLoad(LoadAdError adError) {
            // Handle the failure by logging.
        }
        @Override
        public void onAdClicked() {
            // Log the click event or other custom behavior.
        }
    })
    .build();

Котлин

val adLoader = AdLoader.Builder(this, "/21775744923/example/native")
    // ...
    .withAdListener(object : AdListener() {
        override fun onAdFailedToLoad(adError: LoadAdError) {
            // Handle the failure.
        }
        override fun onAdClicked() {
            // Log the click event or other custom behavior.
        }
    })
    .build()

ImageScaleType

Класс MediaView имеет свойство ImageScaleType при отображении изображений. Если вы хотите изменить масштаб изображения в MediaView , установите соответствующий ImageView.ScaleType с помощью метода setImageScaleType() класса MediaView :

Java

mediaView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);

Котлин

mediaView.imageScaleType = ImageView.ScaleType.CENTER_CROP

Медиаконтент

Класс MediaContent содержит данные, относящиеся к медиаконтенту нативной рекламы, которая отображается с помощью класса MediaView . Когда свойство MediaView класса mediaContent задано экземпляром MediaContent :

  • If a video asset is available, it's buffered and starts playing inside the MediaView . You can tell if a video asset is available by checking hasVideoContent() .

  • If the ad does not contain a video asset, the mainImage asset is downloaded and placed inside the MediaView instead.

Уничтожить рекламу

After you show a native ad, destroy the ad. The following example destroys a native ad:

Java

nativeAd.destroy();

Котлин

nativeAd.destroy()

Тестовый код нативной рекламы

Реклама, продаваемая напрямую

If you'd like to test out what direct-sold native ads are like, you can make use of this Ad Manager ad unit ID:

/21775744923/example/native

It's configured to serve sample app install and content ads, as well as a custom native ad format with the following assets:

  • Заголовок (текст)
  • MainImage (изображение)
  • Подпись (текст)

The template ID for the custom native ad format is 10063170 .

Нативная реклама для заполнения пробелов

Ad Exchange backfill is limited to a select group of publishers. To test the behavior of native backfill ads, use this Ad Manager ad unit:

/21775744923/example/native-backfill

It serves sample app install and content ads that include the AdChoices overlay.

Remember to update your code to refer to your actual ad unit and template IDs before going live.

Примеры на GitHub

Пример полной реализации нативной рекламы:

Java Kotlin JetpackCompose

Следующие шаги

Изучите следующие темы: