네이티브 광고 고급형

NativeAd 표시

네이티브 광고가 로드되면 Google 모바일 광고 SDK가 해당 광고 형식의 리스너를 호출합니다. 그런 다음 앱은 광고를 표시해야 합니다. 하지만 반드시 즉시 수행해야 하는 것은 아닙니다. 디스플레이 광고를 보다 쉽게 구현할 수 있도록 SDK는 몇 가지 유용한 리소스를 제공합니다. 참조하세요.

NativeAdView 클래스

NativeAd 형식의 경우 이에 해당하는 NativeAdView 클래스가 있습니다. 이 클래스는 게시자가 NativeAd의 루트로 사용해야 하는 ViewGroup입니다. 가 단일 NativeAdView는 단일 네이티브 광고에 해당합니다. 해당 광고의 애셋 (ImageView 스크린샷 애셋)은 NativeAdView의 하위 요소여야 합니다. 객체를 지정합니다.

다음은 LinearLayout을 사용하여 애셋 보기를 표시하는 네이티브 광고의 보기 계층 구조에 대한 예입니다.

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

다음은 NativeAdView를 생성하고 여기에 NativeAd를 적용하는 코드의 예입니다.

자바

AdLoader.Builder builder = new AdLoader.Builder(this, "ca-app-pub-3940256099942544/2247696110")
    .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, "ca-app-pub-3940256099942544/2247696110")
    .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)
    }

특정 네이티브 광고의 모든 애셋은 NativeAdView 레이아웃 네이티브 애셋이 네이티브 광고 보기 레이아웃 외부에서 렌더링되면 Google 모바일 광고 SDK에서 경고 기록을 시도합니다.

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

  • 클릭수 기록
  • 첫 번째 픽셀이 화면에 표시될 때의 노출수 기록
  • AdChoices 오버레이 표시

AdChoices 오버레이

SDK가 각 광고 보기에 AdChoices 오버레이를 추가합니다. 다음에 공간 남기기 선호하는 모서리 AdChoices 로고가 자동으로 삽입되는 네이티브 광고 보기 또한 AdChoices 오버레이가 잘 보일 수 있도록 배경 색상을 선택하세요. 적절하게 조정하는 것입니다. 오버레이의 외형과 기능에 대해 자세히 알아보려면 네이티브 광고 필드에 대한 설명을 참고하세요.

광고 표시

보기가 광고임을 나타내는 광고 표시를 적용해야 합니다. 정책 가이드 라인에서 자세히 알아보세요.

코드 예

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

  1. NativeAdView 클래스의 인스턴스를 만듭니다.
  2. 표시될 광고 애셋마다 다음을 수행합니다.

    1. 광고 객체의 애셋으로 애셋 보기를 채웁니다.
    2. NativeAdView 클래스와 함께 애셋 뷰를 등록합니다.
  3. MediaView (네이티브 광고 레이아웃에 대용량 미디어 애셋이 포함된 경우)

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

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

자바

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

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

  1. 레이아웃 확장

    자바

    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
    

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

  2. 애셋 뷰 채우기 및 등록

    이 샘플 코드는 헤드라인을 표시하는 데 사용되는 뷰를 찾고 텍스트를 설정합니다. 를 호출하고 문자열 애셋을 사용하여 NativeAdView 객체:

    자바

    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 클릭 콜백을 구현합니다.

    자바

    AdLoader adLoader = new AdLoader.Builder(context, "ca-app-pub-3940256099942544/2247696110")
        // ...
        .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, "ca-app-pub-3940256099942544/2247696110")
        // ...
        .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와 함께 등록해야 합니다.

    자바

     // 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를 설정하세요.

    자바

    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. 네이티브 광고 객체 등록

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

    자바

    adView.setNativeAd(ad);
    

    Kotlin

    adView.setNativeAd(ad)
    

광고 삭제

네이티브 광고 게재가 끝나면 광고가 다시 게재될 수 있도록 적절하게 가비지 컬렉션됩니다.

자바

nativeAd.destroy();

Kotlin

nativeAd.destroy()

GitHub의 예

네이티브 광고 구현의 전체 예시:

자바 Kotlin

다음 단계

다음 주제를 살펴보세요.