Annonces natives

Lorsqu'une annonce native est chargée, le SDK Google Mobile Ads (bêta) appelle l'écouteur pour le format d'annonce correspondant. Votre application est alors responsable de l'affichage de l'annonce, mais elle n'est pas nécessairement tenue 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 pour 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.libraries.ads.mobile.sdk.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.libraries.ads.mobile.sdk.nativead.NativeAdView>

Jetpack Compose

Incluez le module JetpackComposeDemo/compose-util qui inclut des assistants pour composer NativeAdView et ses composants.

À l'aide du module compose-util, composez 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, développez la vue de l'annonce native et ajoutez-la à la hiérarchie de vues :

Kotlin

// Build an ad request with native ad options to customize the ad.
val adTypes = listOf(NativeAd.NativeAdType.NATIVE)
val adRequest = NativeAdRequest
  .Builder("ca-app-pub-3940256099942544/2247696110", adTypes)
  .build()

val adCallback =
  object : NativeAdLoaderCallback {
    override fun onNativeAdLoaded(nativeAd: NativeAd) {
      activity?.runOnUiThread {

        val nativeAdBinding = NativeAdBinding.inflate(layoutInflater)
        val adView = nativeAdBinding.root
        val frameLayout = myActivityLayout.nativeAdPlaceholder

        // Populate and register the native ad asset views.
        displayNativeAd(nativeAd, nativeAdBinding)

        // Remove all old ad views and add the new native ad
        // view to the view hierarchy.
        frameLayout.removeAllViews()
        frameLayout.addView(adView)
      }
    }
  }

// Load the native ad with our request and callback.
NativeAdLoader.load(adRequest, adCallback)

Java

// Build an ad request with native ad options to customize the ad.
List<NativeAd.NativeAdType> adTypes = Arrays.asList(NativeAd.NativeAdType.NATIVE);
NativeAdRequest adRequest = new NativeAdRequest
                                .Builder("ca-app-pub-3940256099942544/2247696110", adTypes)
                                .build();

NativeAdLoaderCallback adCallback = new NativeAdLoaderCallback() {
    @Override
    public void onNativeAdLoaded(NativeAd nativeAd) {
      if (getActivity() != null) {
        getActivity()
          .runOnUiThread(() -> {
            // Inflate the native ad view and add it to the view hierarchy.
            NativeAdBinding nativeAdBinding = NativeAdBinding.inflate(getLayoutInflater());
            NativeAdView adView = (NativeAdView) nativeAdBinding.getRoot();
            FrameLayout frameLayout = myActivityLayout.nativeAdPlaceholder;

            // Populate and register the native ad asset views.
            displayNativeAd(nativeAd, nativeAdBinding);

            // Remove all old ad views and add the new native ad
            // view to the view hierarchy.
            frameLayout.removeAllViews();
            frameLayout.addView(adView);
        });
      }
    }
};

// Load the native ad with our request and callback.
NativeAdLoader.load(adRequest, adCallback);

Notez que tous les assets d'une annonce native donnée doivent être affichés dans la mise en page NativeAdView. Le SDK Google Mobile Ads (bêta) tente de consigner un avertissement lorsque des éléments 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 élément 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
  • Afficher la superposition "Choisir sa pub"

Afficher l'annonce native

L'exemple suivant montre comment afficher une annonce native :

Kotlin

private fun displayNativeAd(nativeAd: NativeAd, nativeAdBinding : NativeAdBinding) {
  // Set the native ad view elements.
  val nativeAdView = nativeAdBinding.root
  nativeAdView.advertiserView = nativeAdBinding.adAdvertiser
  nativeAdView.bodyView = nativeAdBinding.adBody
  nativeAdView.callToActionView = nativeAdBinding.adCallToAction
  nativeAdView.headlineView = nativeAdBinding.adHeadline
  nativeAdView.iconView = nativeAdBinding.adAppIcon
  nativeAdView.priceView = nativeAdBinding.adPrice
  nativeAdView.starRatingView = nativeAdBinding.adStars
  nativeAdView.storeView = nativeAdBinding.adStore

  // Set the view element with the native ad assets.
  nativeAdBinding.adAdvertiser.text = nativeAd.advertiser
  nativeAdBinding.adBody.text = nativeAd.body
  nativeAdBinding.adCallToAction.text = nativeAd.callToAction
  nativeAdBinding.adHeadline.text = nativeAd.headline
  nativeAdBinding.adAppIcon.setImageDrawable(nativeAd.icon?.drawable)
  nativeAdBinding.adPrice.text = nativeAd.price
  nativeAd.starRating?.toFloat().let { value ->
    nativeAdBinding.adStars.rating = value
  }
  nativeAdBinding.adStore.text = nativeAd.store

  // Hide views for assets that don't have data.
  nativeAdBinding.adAdvertiser.visibility = getAssetViewVisibility(nativeAd.advertiser)
  nativeAdBinding.adBody.visibility = getAssetViewVisibility(nativeAd.body)
  nativeAdBinding.adCallToAction.visibility = getAssetViewVisibility(nativeAd.callToAction)
  nativeAdBinding.adHeadline.visibility = getAssetViewVisibility(nativeAd.headline)
  nativeAdBinding.adAppIcon.visibility = getAssetViewVisibility(nativeAd.icon)
  nativeAdBinding.adPrice.visibility = getAssetViewVisibility(nativeAd.price)
  nativeAdBinding.adStars.visibility = getAssetViewVisibility(nativeAd.starRating)
  nativeAdBinding.adStore.visibility = getAssetViewVisibility(nativeAd.store)

  // Inform Google Mobile Ads SDK (beta) that you have finished populating
  // the native ad views with this native ad.
  nativeAdView.registerNativeAd(nativeAd, nativeAdBinding.adMedia)
}

/**
* Determines the visibility of an asset view based on the presence of its asset.
*
* @param asset The native ad asset to check for nullability.
* @return [View.VISIBLE] if the asset is not null, [View.INVISIBLE] otherwise.
*/
private fun getAssetViewVisibility(asset: Any?): Int {
  return if (asset == null) View.INVISIBLE else View.VISIBLE
}

Java

private void displayNativeAd(ad: NativeAd, nativeAdBinding : NativeAdBinding) {
  // Set the native ad view elements.
  NativeAdView nativeAdView = nativeAdBinding.getRoot();
  nativeAdView.setAdvertiserView(nativeAdBinding.adAdvertiser);
  nativeAdView.setBodyView(nativeAdBinding.adBody);
  nativeAdView.setCallToActionView(nativeAdBinding.adCallToAction);
  nativeAdView.setHeadlineView(nativeAdBinding.adHeadline);
  nativeAdView.setIconView(nativeAdBinding.adAppIcon);
  nativeAdView.setPriceView(nativeAdBinding.adPrice);
  nativeAdView.setStarRatingView(nativeAdBinding.adStars);
  nativeAdView.setStoreView(nativeAdBinding.adStore);

  // Set the view element with the native ad assets.
  nativeAdBinding.adAdvertiser.setText(nativeAd.getAdvertiser());
  nativeAdBinding.adBody.setText(nativeAd.getBody());
  nativeAdBinding.adCallToAction.setText(nativeAd.getCallToAction());
  nativeAdBinding.adHeadline.setText(nativeAd.getHeadline());
  if (nativeAd.getIcon() != null) {
      nativeAdBinding.adAppIcon.setImageDrawable(nativeAd.getIcon().getDrawable());
  }
  nativeAdBinding.adPrice.setText(nativeAd.getPrice());
  if (nativeAd.getStarRating() != null) {
      nativeAdBinding.adStars.setRating(nativeAd.getStarRating().floatValue());
  }
  nativeAdBinding.adStore.setText(nativeAd.getStore());

  // Hide views for assets that don't have data.
  nativeAdBinding.adAdvertiser.setVisibility(getAssetViewVisibility(nativeAd.getAdvertiser()));
  nativeAdBinding.adBody.setVisibility(getAssetViewVisibility(nativeAd.getBody()));
  nativeAdBinding.adCallToAction.setVisibility(getAssetViewVisibility(nativeAd.getCallToAction()));
  nativeAdBinding.adHeadline.setVisibility(getAssetViewVisibility(nativeAd.getHeadline()));
  nativeAdBinding.adAppIcon.setVisibility(getAssetViewVisibility(nativeAd.getIcon()));
  nativeAdBinding.adPrice.setVisibility(getAssetViewVisibility(nativeAd.getPrice()));
  nativeAdBinding.adStars.setVisibility(getAssetViewVisibility(nativeAd.getStarRating()));
  nativeAdBinding.adStore.setVisibility(getAssetViewVisibility(nativeAd.getStore()));

  // Inform Google Mobile Ads SDK (beta) that you have finished populating
  // the native ad views with this native ad.
  nativeAdView.registerNativeAd(nativeAd, nativeAdBinding.adMedia);
}

/**
* Determines the visibility of an asset view based on the presence of its asset.
*
* @param asset The native ad asset to check for nullability.
* @return {@link View#VISIBLE} if the asset is not null, {@link View#INVISIBLE} otherwise.
*/
private int getAssetViewVisibility(Object asset) {
    return (asset == null) ? View.INVISIBLE : View.VISIBLE;
}

Superposition "Choisir sa pub"

Le SDK ajoute une superposition "Choisir sa pub" à chaque vue d'annonce. Laissez de l'espace dans l'angle de votre choix de la vue de votre annonce native pour le logo "Choisir sa pub" inséré automatiquement. Il est également important que la superposition "Choisir sa pub" soit facilement 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 l'overlay, consultez Descriptions des champs des annonces natives.

Attribution des annonces

Vous devez afficher une attribution d'annonce pour indiquer que la vue est une publicité. Pour en savoir plus, consultez nos Consignes relatives au règlement.

Gérer les clics

N'implémentez aucun gestionnaire de clics personnalisé 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 tant que vous remplissez et enregistrez correctement les vues de composants.

Pour écouter les clics, implémentez le rappel de clic du SDK Google Mobile Ads (bêta) :

Kotlin

private fun setEventCallback(nativeAd: NativeAd) {
  nativeAd.adEventCallback =
    object : NativeAdEventCallback {
      override fun onAdClicked() {
        Log.d(Constant.TAG, "Native ad recorded a click.")
      }
    }
}

Java

private void setEventCallback(NativeAd nativeAd) {
  nativeAd.setAdEventCallback(new NativeAdEventCallback() {
      @Override
      public void onAdClicked() {
        Log.d(Constant.TAG, "Native ad recorded a click.");
      }
  });
}

ImageScaleType

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

Kotlin

nativeAdViewBinding.mediaView.imageScaleType = ImageView.ScaleType.CENTER_CROP

Java

nativeAdViewBinding.mediaView.setImageScaleType(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 élément vidéo est disponible, il est mis en mémoire tampon et la lecture commence dans le MediaView. Pour savoir si un élément vidéo est disponible, vérifiez hasVideoContent().

  • Si l'annonce ne contient pas d'asset vidéo, l'asset mainImage est téléchargé et placé dans MediaView.

Détruire une annonce

Une fois que vous avez affiché une annonce native, détruisez-la. L'exemple suivant détruit une annonce native :

Kotlin

nativeAd.destroy()

Java

nativeAd.destroy();

Étapes suivantes

Consultez les rubriques suivantes :

Exemple

Téléchargez et exécutez l'application exemple qui montre comment utiliser le SDK Google Mobile Ads (bêta).