네이티브 광고가 로드되면 Google 모바일 광고 SDK (베타)가 해당 광고 형식의 리스너를 호출합니다. 그런 다음 앱이 광고를 표시해야 하는데, 즉시 표시할 필요는 없습니다. 시스템 정의 광고 형식을 보다 쉽게 표시할 수 있도록 아래와 같은 유용한 리소스를 SDK에서 제공합니다.
NativeAdView
클래스 정의
NativeAdView
클래스를 정의합니다. 이 클래스는 ViewGroup
클래스이며 NativeAdView
클래스의 최상위 컨테이너입니다. 각 네이티브 광고 뷰에는 MediaView
뷰 요소 또는 Title
뷰 요소와 같은 네이티브 광고 확장 소재가 포함되며, 이는 NativeAdView
객체의 하위 요소여야 합니다.
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 Compose
NativeAdView
및 확장 소재를 구성하는 도우미가 포함된 JetpackComposeDemo/compose-util 모듈을 포함합니다.
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.
}
}
로드된 네이티브 광고 처리
네이티브 광고가 로드되면 콜백 이벤트를 처리하고 네이티브 광고 뷰를 확장하고 이 뷰를 뷰 계층 구조에 추가합니다.
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)
자바
// 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);
네이티브 광고의 모든 확장 소재는 NativeAdView
레이아웃 내에서 렌더링해야 합니다. 네이티브 확장 소재가 네이티브 광고 뷰 레이아웃 외부에 렌더링되면 Google 모바일 광고 SDK (베타)가 경고를 로그하려고 시도합니다.
광고 뷰 클래스에서도 개별 확장 소재에 사용되는 뷰를 등록하는 메서드 여러 개와 NativeAd
객체 자체를 등록하는 메서드 1개를 제공합니다.
이 방법으로 뷰를 등록하면 다음과 같은 작업을 SDK가 자동으로 처리할 수 있습니다.
- 클릭수 기록
- 첫 픽셀이 화면에 표시되는 시점에 노출 기록
- AdChoices 오버레이 표시
네이티브 광고 표시
다음 예에서는 네이티브 광고를 표시하는 방법을 보여줍니다.
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
}
자바
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;
}
AdChoices 오버레이
SDK가 각 광고 보기에 AdChoices 오버레이를 추가합니다. 네이티브 광고 뷰에서 원하는 모서리 부분에 AdChoices 로고가 자동으로 삽입될 공간을 남겨두세요. 또한 AdChoices 오버레이가 눈에 잘 띄도록 배경색과 이미지를 적절히 선택하세요. 오버레이의 모양과 기능에 대해 자세히 알아보려면 네이티브 광고 필드에 대한 설명을 참고하세요.
광고 표시
뷰가 광고임을 나타내는 광고 표시를 사용해야 합니다. 정책 가이드라인에서 자세히 알아보세요.
클릭 처리
네이티브 광고 뷰의 위 또는 안에 맞춤 클릭 핸들러를 구현하지 마세요. 올바르게 애셋 보기를 적용하고 등록하면 SDK가 광고 보기 애셋의 클릭을 처리합니다.
클릭을 수신 대기하려면 Google 모바일 광고 SDK (베타) 클릭 콜백을 구현하세요.
Kotlin
private fun setEventCallback(nativeAd: NativeAd) {
nativeAd.adEventCallback =
object : NativeAdEventCallback {
override fun onAdClicked() {
Log.d(Constant.TAG, "Native ad recorded a click.")
}
}
}
자바
private void setEventCallback(NativeAd nativeAd) {
nativeAd.setAdEventCallback(new NativeAdEventCallback() {
@Override
public void onAdClicked() {
Log.d(Constant.TAG, "Native ad recorded a click.");
}
});
}
ImageScaleType
이미지를 표시할 때 MediaView
클래스에는 ImageScaleType
속성이 있습니다. MediaView
에서 이미지의 크기가 조정되는 방식을 변경하려면 MediaView
의 setImageScaleType()
메서드를 사용하여 해당하는 ImageView.ScaleType
을 설정하세요.
Kotlin
nativeAdViewBinding.mediaView.imageScaleType = ImageView.ScaleType.CENTER_CROP
자바
nativeAdViewBinding.mediaView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
MediaContent
MediaContent
클래스에는 MediaView
클래스를 사용하여 표시되는 네이티브 광고의 미디어 콘텐츠와 관련된 데이터가 포함됩니다. MediaView
mediaContent
속성이 MediaContent
인스턴스와 함께 설정된 경우:
사용할 수 있는 동영상 애셋은 버퍼링 후
MediaView
안에서 재생되기 시작합니다.hasVideoContent()
를 확인하면 동영상 애셋을 사용할 수 있는지 알 수 있습니다.광고에 동영상 애셋이 없으면
mainImage
애셋이 대신 다운로드되어MediaView
에 배치됩니다.
광고 소멸시키기
네이티브 광고를 표시한 후 소멸시킵니다. 다음 예에서는 네이티브 광고를 소멸시킵니다.
Kotlin
nativeAd.destroy()
Java
nativeAd.destroy();
다음 단계
다음 주제를 살펴보세요.
예
Google 모바일 광고 SDK (베타)의 사용을 보여 주는 예시 앱을 다운로드하여 실행합니다.