Родной расширенный

Выберите платформу: Android iOS

При загрузке нативной рекламы Google Mobile Ads SDK вызывает прослушиватель для соответствующего формата рекламы. После этого ваше приложение отвечает за отображение рекламы, хотя это не обязательно должно происходить немедленно. Для упрощения отображения системных форматов рекламы 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 Compose

Включите модуль JetpackComposeDemo/compose-util , который содержит помощников для составления NativeAdView и его ресурсов.

Используя модуль compose-util , создайте 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.
        }
    }

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

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

Ява

AdLoader.Builder builder = new AdLoader.Builder(this, "ca-app-pub-3940256099942544/2247696110")
    .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, "ca-app-pub-3940256099942544/2247696110")
    .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 Compose

@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 пытается регистрировать предупреждение, если нативные ресурсы отображаются вне макета представления нативного объявления.

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

  • Запись щелчков
  • Регистрация впечатлений, когда на экране виден первый пиксель
  • Отображение наложения AdChoices

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

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

Ява

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 Compose

@Composable
/** Display a native ad with a user defined template. */
fun DisplayNativeAdView(nativeAd: NativeAd) {
  val context = LocalContext.current
  Box(modifier = Modifier.padding(8.dp).wrapContentHeight(Alignment.Top)) {
    // Call the NativeAdView composable to display the native ad.
    NativeAdView {
      // Inside the NativeAdView composable, display the native ad assets.
      Column(Modifier.align(Alignment.TopStart).wrapContentHeight(Alignment.Top)) {
        // Display the ad attribution.
        NativeAdAttribution(text = context.getString(R.string.attribution))
        Row {
          // 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)
              }
            }
          }
        }

        // If available, display the body asset.
        nativeAd.body?.let { NativeAdBodyView { Text(text = it) } }
        // Display the media asset.
        NativeAdMediaView(Modifier.fillMaxWidth().height(500.dp).fillMaxHeight())

        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.
          // Note: The Jetpack Compose button implements a click handler which overrides the native
          // ad click handler, causing issues. Use the NativeAdButton which does not implement a
          // click handler. To handle native ad clicks, use the NativeAd AdListener onAdClicked
          // callback.
          nativeAd.callToAction?.let { callToAction ->
            NativeAdCallToActionView(Modifier.padding(5.dp)) { NativeAdButton(text = callToAction) }
          }
        }
      }
    }
  }
}

Наложение AdChoices

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

Атрибуция рекламы

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

Обработка щелчков

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

Для отслеживания кликов реализуйте обратный вызов клика Google Mobile Ads SDK:

Ява

AdLoader adLoader = new AdLoader.Builder(context, "ca-app-pub-3940256099942544/2247696110")
    // ...
    .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, "ca-app-pub-3940256099942544/2247696110")
    // ...
    .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 :

Ява

mediaView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);

Котлин

mediaView.imageScaleType = ImageView.ScaleType.CENTER_CROP

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

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

  • Если видео доступно, оно буферизуется и начинается воспроизведение внутри MediaView . Проверить доступность видео можно, проверив hasVideoContent() .

  • Если объявление не содержит видеоактива, вместо него загружается актив mainImage и помещается в MediaView .

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

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

Ява

nativeAd.destroy();

Котлин

nativeAd.destroy()

Примеры на GitHub

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

Java Kotlin JetpackCompose

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

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