Afficher une annonce native

Sélectionnez une plate-forme : Android iOS Android (ancienne version)

Lorsqu'une annonce native se charge, Google Mobile Ads SDK (Legacy) appelle l'écouteur pour le format d'annonce correspondant. Votre application est alors chargée d'afficher l'annonce, mais elle n'est pas obligée de le faire immédiatement. Pour faciliter l'affichage des formats d'annonces définis par le système, le SDK propose des ressources utiles, comme décrit ci-dessous.

Définir la classe NativeAdView

Définissez une classe NativeAdView. Cette classe est une classe ViewGroup et constitue le conteneur de niveau supérieur d'une classe NativeAdView. Chaque vue d'annonce native contient des composants d'annonce native, tels que l'élément de vue MediaView ou l'élément de vue Title, qui doivent être des enfants de l'objet NativeAdView.

Mise en page XML

Ajoutez un NativeAdView XML à votre projet :

<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

  1. Incluez le dossier JetpackCompose Utilities. Ce dossier inclut des assistants pour composer l'objet NativeAdView et les assets.

Rédigez un 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.
        }
    }

Gérer l'annonce native chargée

Lorsqu'une annonce native se charge, gérez l'événement de rappel, gonflez la vue de l'annonce native et ajoutez-la à la hiérarchie des vues :

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);
        }
});

Kotlin

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 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())
}

Notez que tous les composants d'une annonce native donnée doivent être affichés dans la mise en page NativeAdView. Google Mobile Ads SDK (Legacy) tente de consigner un avertissement lorsque des assets natifs sont affichés en dehors d'une mise en page de vue d'annonce native.

Les classes de vue d'annonce fournissent également des méthodes permettant d'enregistrer la vue utilisée pour chaque composant individuel, ainsi qu'une méthode permettant d'enregistrer l'objet NativeAd lui-même. L'enregistrement des vues de cette manière permet au SDK de gérer automatiquement des tâches telles que :

  • Enregistrement des clics
  • Enregistrement des impressions lorsque le premier pixel est visible à l'écran
  • Affichage de la superposition Choisir sa pub pour les créations de remplissage natives (actuellement limité à un groupe d'éditeurs sélectionnés)

Afficher l'annonce native

L'exemple suivant montre comment afficher une annonce native :

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);
}

Kotlin

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) {
  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) }
          }
        }
      }
    }
  }
}

Superposition "Choisir sa pub"

Le SDK ajoute une superposition "Choisir sa pub" en tant que vue d'annonce lorsqu'une annonce de backfill est renvoyée. Si votre application utilise le remplissage d'annonces natives, laissez de l'espace dans l'angle de votre choix de votre vue d'annonce native pour le logo "Choisir sa pub" inséré automatiquement. Il est également important que la superposition "Choisir sa pub" soit visible. Choisissez donc des couleurs et des images d'arrière-plan appropriées. Pour en savoir plus sur l'apparence et le fonctionnement de la superposition, consultez les consignes d'implémentation des annonces natives programmatiques.

Attribution d'annonce pour les annonces natives programmatiques

Lorsque vous diffusez des annonces natives programmatiques, vous devez afficher une attribution d'annonce pour indiquer qu'il s'agit d'une publicité. Pour en savoir plus, consultez nos consignes relatives aux règles.

Gérer les clics

N'implémentez pas de gestionnaires de clics personnalisés sur les vues au-dessus ou à l'intérieur de la vue d'annonce native. Les clics sur les composants de la vue d'annonce sont gérés par le SDK, à condition que vous renseigniez et enregistriez correctement les vues des composants.

Pour écouter les clics, implémentez le rappel de clic Google Mobile Ads SDK (Legacy) :

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();

Kotlin

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

La classe MediaView possède une propriété ImageScaleType lors de l'affichage d'images. Si vous souhaitez modifier la mise à l'échelle d'une image dans le MediaView, définissez le ImageView.ScaleType correspondant à l'aide de la méthode setImageScaleType() du MediaView :

Java

mediaView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);

Kotlin

mediaView.imageScaleType = ImageView.ScaleType.CENTER_CROP

MediaContent

La classe MediaContent contient les données liées au contenu multimédia de l'annonce native, qui est affiché à l'aide de la classe MediaView. Lorsque la propriété MediaView mediaContent est définie avec une instance MediaContent :

  • Si un composant Vidéo est disponible, il est mis en mémoire tampon et commence à être lu dans le MediaView. Vous pouvez vérifier si un composant vidéo est disponible en consultant hasVideoContent().

  • Si l'annonce ne contient pas de composant vidéo, le composant mainImage est téléchargé et placé dans MediaView à la place.

Supprimer une annonce

Une fois l'annonce native affichée, détruisez-la. L'exemple suivant détruit une annonce native :

Java

nativeAd.destroy();

Kotlin

nativeAd.destroy()

Tester le code d'annonce native

Annonces vendues directement

Si vous souhaitez tester les annonces natives vendues en direct, vous pouvez utiliser l'ID de bloc d'annonces Ad Manager suivant :

/21775744923/example/native

Il est configuré pour diffuser des annonces d'installation d'application exemple et des annonces de contenu, ainsi qu'un format d'annonce native personnalisé avec les éléments suivants :

  • Titre (texte)
  • MainImage (image)
  • Légende (texte)

L'ID du modèle pour le format d'annonce native personnalisée est 10063170.

Annonces de backfill natives

Le backfill Ad Exchange est limité à un groupe d'éditeurs sélectionnés. Pour tester le comportement des annonces de backfill natives, utilisez ce bloc d'annonces Ad Manager :

/21775744923/example/native-backfill

Elle diffuse des exemples d'annonces incitant à installer une application et d'annonces de contenu qui incluent la superposition Choisir sa pub.

N'oubliez pas de mettre à jour votre code pour faire référence à vos ID de bloc d'annonces et de modèle réels avant de passer en production.

Exemples sur GitHub

Implémentation complète d'un exemple d'annonce native :

Java Kotlin JetpackCompose

Étapes suivantes

Découvrez les sujets suivants :