네이티브 고급 광고

플랫폼 선택: Android iOS

NativeAd 표시하기

네이티브 광고가 로드되면 Google 모바일 광고 SDK가 해당 광고 형식의 리스너를 호출합니다. 그런 다음 앱이 광고를 표시해야 하는데, 즉시 표시할 필요는 없습니다. 시스템 정의 광고 형식을 보다 쉽게 표시할 수 있도록 SDK에서 아래와 같은 유용한 리소스를 제공합니다.

NativeAdView 클래스 정의하기

NativeAdView 클래스를 정의합니다. 이 클래스는 ViewGroup 클래스이며, NativeAdView 클래스의 최상위 컨테이너입니다. 각 네이티브 광고 뷰에는 MediaView 뷰 요소 또는 Title 뷰 요소와 같은 네이티브 광고 확장 소재가 포함되며, 이는 NativeAdView 객체의 하위 요소여야 합니다.

XML 레이아웃

프로젝트에 XML NativeAdView를 추가합니다.

<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

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.
        }
    }

로드된 네이티브 광고 처리하기

네이티브 광고가 로드되면 콜백 이벤트를 처리하고 네이티브 광고 뷰를 확장하고 뷰 계층 구조에 추가합니다.

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

네이티브 광고의 모든 확장 소재를 NativeAdView 레이아웃 내에서 렌더링해야 합니다. 네이티브 확장 소재가 네이티브 광고 뷰 레이아웃 외부에서 렌더링되면 Google 모바일 광고 SDK가 경고 기록을 시도합니다.

광고 뷰 클래스에서도 각 개별 확장 소재에 사용되는 뷰를 등록하는 메서드 여러 개와 NativeAd 객체 자체를 등록하는 메서드 1개를 제공합니다. 이 방법으로 보기를 등록하면 다음과 같은 작업을 SDK가 자동으로 처리할 수 있습니다.

  • 클릭수 기록
  • 노출수 기록(첫 픽셀이 화면에 표시되는 시점)
  • 네이티브 예비 광고 소재의 AdChoices 오버레이 표시 (현재는 일부 게시자만 가능)

AdChoices 오버레이

예비 광고가 반환될 때 SDK가 AdChoices 오버레이를 광고 뷰로 추가합니다. 앱에서 예비 네이티브 광고를 사용하려면 네이티브 광고 뷰에서 원하는 모서리 부분에 AdChoices 로고가 자동으로 삽입될 공간을 남겨둡니다. 또한 AdChoices 오버레이가 표시되도록 배경색과 이미지를 적절히 선택해야 합니다. 오버레이의 모양과 기능에 대한 자세한 내용은 프로그래매틱 네이티브 광고 구현 가이드라인을 참고하세요.

프로그래매틱 네이티브 광고의 광고 표시

프로그래매틱 네이티브 광고를 표시할 때 광고임을 나타내는 표시를 넣어야 합니다. 정책 가이드 라인에서 자세히 알아보세요.

코드 예

다음은 네이티브 광고를 표시하는 방법입니다.

  1. NativeAdView 클래스의 인스턴스를 만듭니다.
  2. 게재될 광고 확장 소재마다 다음을 수행합니다.

    1. 광고 객체의 확장 소재로 확장 소재 뷰를 채웁니다.
    2. NativeAdView 클래스로 확장 소재 뷰를 등록합니다.
  3. 네이티브 광고 레이아웃에 대용량 미디어 확장 소재가 포함되어 있으면 MediaView를 등록합니다.

  4. NativeAdView 클래스와 함께 광고 객체를 등록합니다.

다음은 NativeAd를 표시하는 함수의 예입니다.

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 the app is using a MediaView, it should be
  // instantiated and passed to setMediaView. This view is a little different
  // in that the asset is populated automatically, so there's one less step.
  MediaView mediaView = (MediaView) adView.findViewById(R.id.ad_media);
  adView.setMediaView(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);
}

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) {
  val context = LocalContext.current
  Box(modifier = Modifier.padding(8.dp).wrapContentHeight(Alignment.Top)) {
    // Call the NativeAdView composable to display the native ad.
    NativeAdView {
      // Inside the NativeAdView composable, display the native ad assets.
      Column(Modifier.align(Alignment.TopStart).wrapContentHeight(Alignment.Top)) {
        // Display the ad attribution.
        NativeAdAttribution(text = context.getString(R.string.attribution))
        Row {
          // 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)
              }
            }
          }
        }

        // If available, display the body asset.
        nativeAd.body?.let { NativeAdBodyView { Text(text = it) } }
        // Display the media asset.
        NativeAdMediaView(Modifier.fillMaxWidth().height(500.dp).fillMaxHeight())

        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.
          // Note: The Jetpack Compose button implements a click handler which overrides the native
          // ad click handler, causing issues. Use the NativeAdButton which does not implement a
          // click handler. To handle native ad clicks, use the NativeAd AdListener onAdClicked
          // callback.
          nativeAd.callToAction?.let { callToAction ->
            NativeAdCallToActionView(Modifier.padding(5.dp)) { NativeAdButton(text = callToAction) }
          }
        }
      }
    }
  }
}

개별 작업은 다음과 같습니다.

  1. 레이아웃 확장

    Java

    LayoutInflater inflater = (LayoutInflater) parent.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    NativeAdView adView = (NativeAdView) inflater
            .inflate(R.layout.ad_layout_file, parent);
    

    Kotlin

    val inflater = parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)
            as LayoutInflater
    val adView = inflater.inflate(R.layout.ad_layout_file, parent) as NativeAdView
    

    이 코드는 네이티브 광고를 표시한 다음 NativeAdView에 대한 참조의 위치를 찾는 뷰가 포함된 XML 레이아웃을 확장합니다. 프래그먼트나 활동에 NativeAdView가 있거나 레이아웃 파일을 사용하지 않고 동적으로 인스턴스를 만든 경우, 기존의 객체를 재사용할 수 있습니다.

  2. 확장 소재 뷰 채우기 및 등록

    이 샘플 코드에서는 광고 제목을 표시하는 데 사용되는 보기의 위치를 찾고, 광고 객체가 제공하는 문자열 애셋을 이용해 문구를 설정하며, 이를 아래의 NativeAdView객체와 함께 등록합니다.

    Java

    TextView headlineView = adView.findViewById<TextView>(R.id.ad_headline);
    headlineView.setText(ad.getHeadline());
    adView.setHeadlineView(headlineView);
    

    Kotlin

    val headlineView = adView.findViewById<TextView>(R.id.ad_headline)
    headlineView.text = ad.headline
    adView.headlineView = headlineView
    

    앱에서 게재하는 네이티브 광고 객체가 제공하는 확장 소재별로 뷰의 위치를 찾고, 값을 설정하며, 이를 광고 뷰 클래스와 함께 등록하는 과정을 반복해야 합니다.

  3. 클릭 처리

    네이티브 광고 뷰의 위 또는 안에서는 맞춤 클릭 핸들러를 구현하지 마세요. 이전 섹션의 설명대로, 올바르게 확장 소재 뷰를 채우고 등록하면 SDK가 광고 뷰 확장 소재의 클릭을 처리합니다.

    클릭을 수신 대기하려면 Google 모바일 광고 SDK 클릭 콜백을 구현하세요.

    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()
    
  4. MediaView 등록하기

    네이티브 광고의 레이아웃에 기본 이미지 확장 소재를 포함하려면 ImageView 확장 소재 대신 MediaView 확장 소재를 사용해야 합니다.

    MediaView는 기본 미디어 확장 소재(동영상 또는 이미지)를 표시하도록 설계된 특수 View입니다.

    MediaView는 XML 레이아웃에서 정의하거나 동적으로 생성할 수 있으며, 다른 확장 소재 뷰와 마찬가지로 NativeAdView의 뷰 계층 구조 안에 위치해야 합니다. MediaView를 사용하는 앱은 NativeAdView로 등록해야 합니다.

    Java

     // Populate and register the media asset view.
     nativeAdView.setMediaView(nativeAdBinding.adMedia);
    

    Kotlin

     // Populate and register the media asset view.
     nativeAdView.mediaView = nativeAdBinding.adMedia
    

    ImageScaleType

    이미지를 표시할 때 MediaView 클래스에는 ImageScaleType 속성이 있습니다. MediaView에서 이미지의 크기가 조정되는 방식을 변경하려면 MediaViewsetImageScaleType() 메서드를 사용하여 해당하는 ImageView.ScaleType을 설정합니다.

    Java

    mediaView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
    

    Kotlin

    mediaView.imageScaleType = ImageView.ScaleType.CENTER_CROP
    

    MediaContent

    MediaContent 클래스에는 MediaView 클래스를 사용하여 표시되는 네이티브 광고의 미디어 콘텐츠와 관련된 데이터가 포함됩니다. MediaView mediaContent 속성이 MediaContent 인스턴스와 함께 설정된 경우:

    • 사용할 수 있는 동영상 애셋은 버퍼링 후 MediaView 안에서 재생되기 시작합니다. hasVideoContent()를 확인하면 동영상 애셋을 사용할 수 있는지 알 수 있습니다.

    • 광고에 동영상 애셋이 없으면 mainImage 애셋이 대신 다운로드되어 MediaView에 배치됩니다.

    기본적으로 mainImage는 처음 다운로드한 이미지 확장 소재입니다. setReturnUrlsForImageAssets(true)를 사용하면 mainImagenull이며 mainImage 속성을 직접 다운로드한 이미지에 설정해야 합니다. 사용 가능한 동영상 애셋이 없는 경우에만 이 이미지가 사용됩니다.

  5. 네이티브 광고 객체 등록

    마지막 단계로, 네이티브 광고 객체를 표시하는 뷰와 함께 네이티브 광고 객체를 등록합니다.

    Java

    adView.setNativeAd(ad);
    

    Kotlin

    adView.setNativeAd(ad)
    

광고 삭제하기

네이티브 광고를 표시한 후 광고를 삭제합니다. 다음 예에서는 네이티브 광고를 삭제합니다.

Java

nativeAd.destroy();

Kotlin

nativeAd.destroy()

네이티브 광고 코드 테스트

직접 판매 광고

직접 판매된 네이티브 광고가 어떤 광고인지 테스트하고 싶다면 아래의 Ad Manager 광고 단위 ID를 사용해 보세요.

/21775744923/example/native

이 ID는 샘플 앱 설치 및 콘텐츠 광고는 물론 다음 애셋이 포함된 맞춤 네이티브 광고 형식을 게재하도록 구성되었습니다.

  • 광고 제목(텍스트)
  • 기본 이미지(이미지)
  • 캡션(텍스트)

맞춤 네이티브 광고 형식의 템플릿 ID는 10063170입니다.

네이티브 예비 광고

Ad Exchange 예비 광고는 일부 게시자에게만 제공되고 있습니다. 네이티브 예비 광고의 작동을 테스트하려면 다음과 같은 Ad Manager 광고 단위를 사용하세요.

/21775744923/example/native-backfill

이 광고 단위에서는 AdChoices 오버레이가 적용된 앱 설치 및 콘텐츠 샘플 광고가 게재됩니다.

광고 단위를 게시하기 전에 실제 광고 단위 및 형식 ID를 참조하도록 코드를 업데이트해야 합니다.

GitHub의 예

완전한 네이티브 광고 구현의 예시는 다음과 같습니다.

Java Kotlin JetpackCompose

다음 단계

다음 주제를 살펴보세요.