When a native ad loads, GMA Next-Gen SDK invokes the listener for the corresponding ad format. Your app is then responsible for displaying the ad, though it doesn't necessarily have to do so immediately. To make displaying system-defined ad formats easier, the SDK offers some useful resources, as described below.
Определите класс NativeAdView
Define a NativeAdView class. This class is a ViewGroup class and is the top level container for a NativeAdView class. Each native ad view contains native ad assets, such as the MediaView view element or the Title view element, which must be a child of the NativeAdView object.
XML-макет
Добавьте XML- NativeAdView в свой проект:
<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
- Include the JetpackCompose Utilities folder. This folder includes helpers for composing the
NativeAdViewobject 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:
Котлин
// 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);
Note that all assets for a given native ad should be rendered inside the NativeAdView layout. GMA Next-Gen SDK attempts to log a warning when native assets are rendered outside of a native ad view layout.
The ad view classes also provide methods used to register the view used for each individual asset, and one to register the NativeAd object itself. Registering the views in this way allows the SDK to automatically handle tasks such as:
- Запись щелчков
- Recording impressions when the first pixel is visible on the screen
- Отображение всплывающего окна AdChoices
Показать нативную рекламу
The following example demonstrates how to display a native ad:
Котлин
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 GMA Next-Gen SDK 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 GMA Next-Gen SDK 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;
}
Наложение AdChoices
An AdChoices overlay is added to each ad view by the SDK. Leave space in your preferred corner of your native ad view for the automatically inserted AdChoices logo. Also, it's important that the AdChoices overlay be seen, so choose background colors and images appropriately. For more information on the overlay's appearance and function, see Native ads field descriptions .
Атрибуция рекламы
You must display an ad attribution to denote that the view is an advertisement. Learn more in our policy guidelines .
Обработка кликов
Don't implement any custom click handlers on any views over or within the native ad view. Clicks on the ad view assets are handled by the SDK as long as you correctly populate and register the asset views.
To listen for clicks, implement GMA Next-Gen SDK click callback:
Котлин
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
The MediaView class has an ImageScaleType property when displaying images. If you want to change how an image is scaled in the MediaView , set the corresponding ImageView.ScaleType using the setImageScaleType() method of the MediaView :
Котлин
nativeAdViewBinding.mediaView.imageScaleType = ImageView.ScaleType.CENTER_CROP
Java
nativeAdViewBinding.mediaView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
Медиаконтент
The MediaContent class holds the data related to the media content of the native ad, which is displayed using the MediaView class. When the MediaView mediaContent property is set with a MediaContent instance:
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 checkinghasVideoContent().If the ad does not contain a video asset, the
mainImageasset is downloaded and placed inside theMediaViewinstead.
Добавить креативное резюме
In conversational and AI chat applications, GMA Next-Gen SDK provides a creative summary asset ( creativeSummary ) for the ad creative. You can integrate ads into your app's chat flows with an introductory message.
Добавьте текстовое поле в свой макет.
Add a TextView for the creative summary asset inside your NativeAdView container layout:
<TextView
android:id="@+id/ad_creative_summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="13sp" />
Заполните и зарегистрируйте представление.
Populate the TextView with creativeSummary and register it with the creativeSummaryView property on your NativeAdView object. Registering the view enables automatic click tracking for the creative summary asset.
Котлин
Java
Отслеживание кликов и измененный текст
- Direct rendering: When you render the exact
creativeSummarystring provided by the SDK, register it to thecreativeSummaryViewproperty inside theNativeAdViewcontainer to enable SDK click handling. - Modified introductions: If your app modifies, summarizes, or appends custom conversational text to the creative summary, place the modified text outside the
NativeAdViewcontainer.
Уничтожить рекламу
After you show a native ad, destroy the ad. The following example destroys a native ad:
Котлин
nativeAd.destroy()
Java
nativeAd.destroy();
Следующие шаги
Изучите следующие темы:
Пример
Загрузите и запустите пример приложения , демонстрирующий использование GMA Next-Gen SDK .