NativeAd 표시
네이티브 광고가 로드되면 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.
}
}
로드된 네이티브 aad 처리
네이티브 광고가 로드되면 콜백 이벤트를 처리하고 네이티브 광고 뷰를 확장한 후 뷰 계층 구조에 추가합니다.
Kotlin
// Build an ad request with native ad options to customize the ad.
val adTypes = listOf(NativeAd.NativeAdType.NATIVE)
val adRequest = NativeAdRequest
.Builder("/21775744923/example/native", 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("/21775744923/example/native", 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 오버레이 표시(현재는 일부 게시자만 가능)
AdChoices 오버레이
백업 광고가 반환될 때 SDK가 AdChoices 오버레이를 광고 보기로 추가합니다. 앱에서 네이티브 광고의 백업 광고를 사용하는 경우 네이티브 광고 보기의 원하는 모서리 부분에 AdChoices 로고가 자동으로 삽입될 공간을 남겨두세요. 또한 AdChoices 오버레이가 눈에 잘 띄도록 배경색과 이미지를 적절히 선택하세요. 오버레이의 모양과 기능에 대한 자세한 내용은 프로그래매틱 네이티브 광고 구현 가이드라인을 참고하세요.
프로그래매틱 네이티브 광고의 광고 표시
프로그래매틱 네이티브 광고를 표시할 때 광고임을 나타내는 표시를 넣어야 합니다. 정책 가이드라인에서 자세히 알아보세요.
코드 예
다음은 네이티브 광고를 표시하는 방법입니다.
NativeAdView
클래스의 인스턴스를 만듭니다.표시될 광고 애셋마다 다음을 실행합니다.
- 광고 객체의 애셋으로 애셋 보기를 채웁니다.
NativeAdView
클래스와 함께 애셋 보기를 등록합니다.
NativeAdView
클래스와 함께 광고 객체를 등록합니다.
다음은 NativeAd
를 표시하는 함수의 예입니다.
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 the Google Mobile Ads 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
}
자바
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 the Google Mobile Ads 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;
}
개별 작업은 다음과 같습니다.
레이아웃 확장
Kotlin
// Remove all old ad views when loading a new native ad. binding.nativeViewContainer.removeAllViews() // Inflate the native ad view and add it to the view hierarchy. val nativeAdBinding = NativeAdBinding.inflate(layoutInflater) binding.nativeViewContainer.addView(nativeAdBinding.root)
자바
// Remove all old ad views when loading a new native ad. binding.nativeViewContainer.removeAllViews(); // Inflate the native ad view and add it to the view hierarchy. NativeAdBinding nativeAdBinding = NativeAdBinding.inflate(getLayoutInflater()); binding.nativeViewContainer.addView(nativeAdBinding.getRoot());
이 코드는 네이티브 광고를 표시하는 뷰가 포함된 XML 레이아웃을 확장한 다음
NativeAdView
에 대한 참조를 찾습니다. 조각이나 활동에NativeAdView
가 있거나 레이아웃 파일을 사용하지 않고 동적으로 인스턴스를 만든 경우, 기존의 객체를 재사용할 수 있습니다.애셋 뷰 채우기 및 등록
이 샘플 코드에서는 광고 제목을 표시하는 데 사용되는 보기의 위치를 찾고, 광고 객체가 제공하는 문자열 애셋을 이용해 문구를 설정하며, 이를
NativeAdView
객체와 함께 등록합니다.Kotlin
nativeAdView.headlineView = nativeAdBinding.adHeadline nativeAdBinding.adHeadline.text = nativeAd.headline nativeAdBinding.adHeadline.visibility = getAssetViewVisibility(nativeAd.headline)
자바
nativeAdView.setHeadlineView(nativeAdBinding.adHeadline); nativeAdBinding.adHeadline.setText(nativeAd.getHeadline()); nativeAdBinding.adHeadline.setVisibility(getAssetViewVisibility(nativeAd.getHeadline()));
앱에서 표시하는 네이티브 광고 객체가 제공하는 애셋별로 보기의 위치를 찾고, 값을 설정하며, 이를 광고 보기 클래스와 함께 등록하는 과정을 반복해야 합니다.
클릭 처리
네이티브 광고 보기의 위 또는 안에는 맞춤 클릭 핸들러를 구현하지 마세요. 이전 섹션의 설명대로, 올바르게 애셋 보기를 채우고 등록하면 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."); } }); }
MediaView 등록
네이티브 광고의 레이아웃에 기본 이미지 애셋을 포함하려면
ImageView
애셋 대신MediaView
애셋을 사용해야 합니다.Kotlin
// Get the media asset view. val mediaView = nativeAdBinding.adMedia
자바
// Get the media asset view. MediaView mediaView = nativeAdBinding.adMedia;
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
에 배치됩니다.
disableImageDownloading(true)
를 사용하면mainImage
는null
이며mainImage
속성을 직접 다운로드한 이미지에 설정해야 합니다. 사용 가능한 동영상 애셋이 없는 경우에만 이 이미지를 사용합니다.네이티브 광고 객체 등록
마지막 단계이며, 네이티브 광고 객체를 표시하는 보기와 함께 미디어 콘텐츠 애셋의 보기와 함께 네이티브 광고 객체를 등록합니다.
Kotlin
// Inform the Google Mobile Ads SDK that you have finished populating // the native ad views with this native ad and media content asset. nativeAdView.registerNativeAd(nativeAd, mediaView)
자바
// Inform the Google Mobile Ads SDK that you have finished populating // the native ad views with this native ad and media content asset. nativeAdView.registerNativeAd(nativeAd, mediaView);
광고 삭제
네이티브 광고 게재가 끝나면 광고가 올바르게 폐기되도록 광고를 삭제해야 합니다.
Kotlin
nativeAd.destroy()
자바
nativeAd.destroy();
네이티브 광고 코드 테스트
직접 판매 광고
직접 판매된 네이티브 광고가 어떤 광고인지 테스트하고 싶다면 아래의 Ad Manager 광고 단위 ID를 사용해 보세요.
/21775744923/example/native
이 ID는 샘플 앱 설치 및 콘텐츠 광고는 물론 다음 애셋이 포함된 맞춤 네이티브 광고 형식을 게재하도록 구성되었습니다.
- 광고 제목 (텍스트)
- 기본 이미지 (이미지)
- 캡션 (텍스트)
맞춤 네이티브 광고 형식의 템플릿 ID는 10063170
입니다.
네이티브 백업 광고
Ad Exchange 백업 광고는 일부 게시자에게만 제공됩니다. 네이티브 백업 광고의 작동을 테스트하려면 다음과 같은 Ad Manager 광고 단위를 사용하세요.
/21775744923/example/native-backfill
이 광고 단위에서는 AdChoices 오버레이가 적용된 앱 설치 및 콘텐츠 샘플 광고가 게재됩니다.
광고 단위를 게시하기 전에 실제 광고 단위 및 템플릿 ID를 참조하도록 코드를 업데이트해야 합니다.
다음 단계
다음 주제를 살펴보세요.
예
차세대 Google 모바일 광고 SDK 사용을 보여주는 예시 앱을 다운로드하여 실행합니다.