Android 앱에 네이티브 광고 추가

네이티브 배너 광고 API를 사용하면 광고주의 크리에이티브 자산(예: 이미지, 동영상, 슬라이드 콘텐츠) 없이 네이티브 광고를 표시하는 맞춤 설정 경험을 빌드할 수 있습니다. 네이티브 광고와 마찬가지로 여러 가지 광고 속성(예: 제목, 아이콘, 행동 유도)을 받게 되고, 이를 사용하여 광고를 표시할 곳에 맞춤 설정된 보기를 구성합니다. 그러나 배너 광고와 달리, 네이티브 배너 광고 API는 네이티브 레이아웃 경험을 제공하므로 광고가 아니라 구성 요소 레이아웃 맞춤 설정을 완전히 제어할 수 있습니다.

계속하기 전에 Audience Network 시작하기Android 시작하기 가이드를 완료했는지 확인하세요.

이 가이드에서는 다음의 네이티브 배너 광고 노출 위치를 구현합니다. 다음의 구성 요소를 사용하여 네이티브 배너 광고를 만들어보겠습니다.

보기 #1: AdOptionsView

보기 #2: Sponsored 레이블

보기 #3: 광고 아이콘

보기 #4: 광고 제목

보기 #5: 소셜 컨텍스트

보기 #6: 행동 유도 버튼




네이티브 배너 광고 단계

1단계: 네이티브 배너 광고 요청

2단계: 네이티브 배너 광고 레이아웃 만들기

3단계: 광고 메타데이터를 사용하여 레이아웃 채우기

Audience Network SDK 초기화

이 메서드는 Android Audience Network SDK 버전 5.1에 추가되었습니다.

5.3.0 버전 이상에서는 Audience Network Android SDK의 명시적 초기화가 필수입니다. Audience Network Android SDK를 초기화하는 방법은 이 문서를 참조하세요.

개체를 만들고 광고를 읽어들이기 전에 먼저 Audience Network SDK를 초기화해야 합니다. 이 작업은 앱 실행 시에 하는 것이 좋습니다.

public class YourApplication extends Application {
    ...
    @Override
    public void onCreate() {
        super.onCreate();
        // Initialize the Audience Network SDK
        AudienceNetworkAds.initialize(this);       
    }
    ...
}

1단계: 네이티브 배너 광고 요청

활동의 맨 위에 다음 코드를 추가하여 Facebook 광고 SDK를 가져옵니다.

import com.facebook.ads.*;

그런 다음, NativeBannerAd 개체를 인스턴스화하고 AdListener를 만들어 활동에서 loadAd(...)를 호출합니다.

public class NativeBannerAdActivity extends Activity {

    private final String TAG = NativeBannerAdActivity.class.getSimpleName();
    private NativeBannerAd nativeBannerAd;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Instantiate a NativeBannerAd object. 
        // NOTE: the placement ID will eventually identify this as your App, you can ignore it for
        // now, while you are testing and replace it later when you have signed up.
        // While you are using this temporary code you will only get test ads and if you release
        // your code like this to the Google Play your users will not receive ads (you will get a no fill error).
        nativeBannerAd = new NativeBannerAd(this, "YOUR_PLACEMENT_ID");
        NativeAdListener nativeAdListener = new NativeAdListener() {

            @Override
            public void onMediaDownloaded(Ad ad) {
                // Native ad finished downloading all assets
                Log.e(TAG, "Native ad finished downloading all assets.");
            }

            @Override
            public void onError(Ad ad, AdError adError) {
                // Native ad failed to load
                Log.e(TAG, "Native ad failed to load: " + adError.getErrorMessage());
            }

            @Override
            public void onAdLoaded(Ad ad) {
                // Native ad is loaded and ready to be displayed
                Log.d(TAG, "Native ad is loaded and ready to be displayed!");
            }

            @Override
            public void onAdClicked(Ad ad) {
                // Native ad clicked
                Log.d(TAG, "Native ad clicked!");
            }

            @Override
            public void onLoggingImpression(Ad ad) {
                // Native ad impression
                Log.d(TAG, "Native ad impression logged!");
            }
        });
        // load the ad
        nativeBannerAd.loadAd(
                nativeBannerAd.buildLoadAdConfig()
                        .withAdListener(nativeAdListener)
                        .build());
    }
}

나중에 다시 돌아와 onAdLoaded() 메서드에 코드를 추가할 것입니다.

2단계: 네이티브 배너 광고 레이아웃 만들기

다음 단계에서는 광고 메타데이터를 추출하고 해당 속성을 사용하여 맞춤 설정 네이티브 UI를 빌드합니다. 레이아웃 .xml에서 맞춤 설정 보기를 만들거나 코드에 요소를 추가할 수 있습니다.

앱에서 네이티브 배너 광고를 디자인할 때 네이티브 광고 가이드라인을 참조하세요.

활동의 레이아웃 activity_main.xml에서 네이티브 배너 광고의 컨테이너를 추가합니다. 컨테이너는 com.facebook.ads.NativeAdLayout이어야 합니다. 이는 FrameLayout을 기반으로 하고 광고 위에서 네이티브 광고 보고 플로를 렌더링할 수 있는 몇 가지 추가 기능이 포함된 래퍼입니다. 나중에 onAdLoaded() 메서드에서 이 컨테이너에 네이티브 광고 보기를 채워야 합니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    ...
    <com.facebook.ads.NativeAdLayout
        android:id="@+id/native_banner_ad_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" />
    ...
</RelativeLayout>

네이티브 배너 광고를 위한 맞춤 설정 레이아웃 native_banner_ad_unit.xml을 만듭니다.



네이티브 배너 광고의 맞춤 설정 레이아웃의 예는 다음과 같습니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RelativeLayout
            android:id="@+id/ad_choices_container"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="2dp" />

        <TextView
            android:id="@+id/native_ad_sponsored_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:ellipsize="end"
            android:lines="1"
            android:padding="2dp"
            android:textColor="@android:color/darker_gray"
            android:textSize="12sp" />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white">

        <com.facebook.ads.MediaView
            android:id="@+id/native_icon_view"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:gravity="center" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:orientation="vertical"
            android:paddingLeft="53dp"
            android:paddingRight="83dp">

            <TextView
                android:id="@+id/native_ad_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:lines="1"
                android:textColor="@android:color/black"
                android:textSize="15sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/native_ad_social_context"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:lines="1"
                android:textSize="12sp" />
        </LinearLayout>

        <Button
            android:id="@+id/native_ad_call_to_action"
            android:layout_width="80dp"
            android:layout_height="50dp"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:background="#4286F4"
            android:gravity="center"
            android:paddingLeft="3dp"
            android:paddingRight="3dp"
            android:textColor="@android:color/white"
            android:textSize="12sp"
            android:visibility="gone" />

    </RelativeLayout>
</LinearLayout>

3단계: 광고 메타데이터를 사용하여 레이아웃 채우기

시나리오 1: 광고가 성공적으로 읽어들여지면 즉시 표시합니다. 위의 onAdLoaded() 메서드를 수정하여 Native Banner Ad's 속성을 가져오고 아래와 같이 표시합니다.

public class NativeBannerAdActivity extends Activity {

    private NativeAdLayout nativeAdLayout;
    private LinearLayout adView;
    private NativeBannerAd nativeBannerAd;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Instantiate a NativeBannerAd object. 
        // NOTE: the placement ID will eventually identify this as your App, you can ignore it for
        // now, while you are testing and replace it later when you have signed up.
        // While you are using this temporary code you will only get test ads and if you release
        // your code like this to the Google Play your users will not receive ads (you will get a no fill error).
        nativeBannerAd = new NativeBannerAd(this, "YOUR_PLACEMENT_ID");
        NativeAdListener nativeAdListener = new NativeAdListener() {
            ...
            @Override
            public void onAdLoaded(Ad ad) {
                // Race condition, load() called again before last ad was displayed
                if (nativeBannerAd == null || nativeBannerAd != ad) {
                    return;
                 }
                // Inflate Native Banner Ad into Container
                inflateAd(nativeBannerAd);
            }
            ...
        });
        // load the ad
        nativeBannerAd.loadAd(
                nativeBannerAd.buildLoadAdConfig()
                        .withAdListener(nativeAdListener)
                        .build());
    }

    private void inflateAd(NativeBannerAd nativeBannerAd) {
        // Unregister last ad
        nativeBannerAd.unregisterView();

        // Add the Ad view into the ad container.
        nativeAdLayout = findViewById(R.id.native_banner_ad_container);
        LayoutInflater inflater = LayoutInflater.from(NativeBannerAdActivity.this);
        // Inflate the Ad view.  The layout referenced is the one you created in the last step.
        adView = (LinearLayout) inflater.inflate(R.layout.native_banner_ad_layout, nativeAdLayout, false);
        nativeAdLayout.addView(adView);

        // Add the AdChoices icon
        RelativeLayout adChoicesContainer = adView.findViewById(R.id.ad_choices_container);
        AdOptionsView adOptionsView = new AdOptionsView(NativeBannerAdActivity.this, nativeBannerAd, nativeAdLayout);
        adChoicesContainer.removeAllViews();
        adChoicesContainer.addView(adOptionsView, 0);

        // Create native UI using the ad metadata.
        TextView nativeAdTitle = adView.findViewById(R.id.native_ad_title);
        TextView nativeAdSocialContext = adView.findViewById(R.id.native_ad_social_context);
        TextView sponsoredLabel = adView.findViewById(R.id.native_ad_sponsored_label);
        MediaView nativeAdIconView = adView.findViewById(R.id.native_icon_view);
        Button nativeAdCallToAction = adView.findViewById(R.id.native_ad_call_to_action);

        // Set the Text.
        nativeAdCallToAction.setText(nativeBannerAd.getAdCallToAction());
        nativeAdCallToAction.setVisibility(
                nativeBannerAd.hasCallToAction() ? View.VISIBLE : View.INVISIBLE);
        nativeAdTitle.setText(nativeBannerAd.getAdvertiserName());
        nativeAdSocialContext.setText(nativeBannerAd.getAdSocialContext());
        sponsoredLabel.setText(nativeBannerAd.getSponsoredTranslation());

        // Register the Title and CTA button to listen for clicks.
        List<View> clickableViews = new ArrayList<>();
        clickableViews.add(nativeAdTitle);
        clickableViews.add(nativeAdCallToAction);
        nativeBannerAd.registerViewForInteraction(adView, nativeAdIconView, clickableViews);
    }
}

SDK에서 노출을 로깅하고 클릭을 자동으로 처리합니다. 이를 사용하려면 NativeBannerAd 인스턴스로 광고 보기를 등록해야 합니다. 광고 요소를 클릭할 수 있도록 하려면 다음을 통해 등록합니다.

registerViewForInteraction(View view, MediaView adIconView)

시나리오 2: 광고가 성공적으로 읽어들여지면 몇 초 또는 몇 분 이내에 광고가 표시됩니다. 광고가 표시되기 전에 무효화되지 않았는지 확인해야 합니다.

광고가 로드된 후 즉시 표시되지 않는 경우 개발자는 광고의 무효화 여부를 확인해야 합니다. 광고가 성공적으로 로드되면 60분간 유효합니다. 무효화된 광고를 표시하면 후원을 받지 합니다. 광고를 검증하려면 isAdInvalidated()를 호출해야 합니다.

아래의 아이디어를 따르되 코드는 예시일 뿐이므로 코드를 프로젝트에 복사하지 마세요.

public class NativeBannerAdActivity extends Activity {

    private NativeBannerAd nativeBannerAd;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Instantiate a NativeBannerAd object. 
        // NOTE: the placement ID will eventually identify this as your App, you can ignore it for
        // now, while you are testing and replace it later when you have signed up.
        // While you are using this temporary code you will only get test ads and if you release
        // your code like this to the Google Play your users will not receive ads (you will get a no fill error).
        nativeBannerAd = new NativeBannerAd(this, "YOUR_PLACEMENT_ID");
         NativeAdListener nativeAdListener = new NativeAdListener() {
            ...
        });
        // load the ad
        nativeBannerAd.loadAd(
                nativeBannerAd.buildLoadAdConfig()
                        .withAdListener(nativeAdListener)
                        .build());
    }

    private void showAdWithDelay() {
       /**
        * Here is an example for displaying the ad with delay;
        * Please do not copy the Handler into your project
       */
       // Handler handler = new Handler();
       handler.postDelayed(new Runnable() {
           public void run() {
             // Check if nativeBannerAd has been loaded successfully
               if(nativeBannerAd == null || !nativeBannerAd.isAdLoaded()) {
                   return;
               }
             // Check if ad is already expired or invalidated, and do not show ad if that is the case. You will not get paid to show an invalidated ad.
               if(nativeBannerAd.isAdInvalidated()) {
                   return;
               }
               inflateAd(nativeBannerAd); // Inflate Native Banner Ad into Container same as in previous code example
           }
       }, 1000 * 60 * 15); // Show the ad after 15 minutes
    }
}

클릭 가능한 영역 제어

사용자 환경을 개선하고 더 나은 결과를 얻으려면 항상 광고의 클릭 가능한 영역을 제어하여 의도치 않은 클릭을 피해야 합니다. 클릭할 수 없는 여백 정책에 대한 자세한 내용은 Audience Network SDK 정책을 참조하세요.

클릭 가능한 영역을 더욱 세밀하게 제어하려면 registerViewForInteraction(View view, MediaView adIconView, List<View> clickableViews)를 사용하여 클릭 가능한 보기 리스트를 등록합니다. 예를 들어 위의 예시에서 광고 제목과 행동 유도 버튼만 클릭할 수 있도록 하려면 다음과 같이 코드를 작성합니다.

@Override
public void onAdLoaded(Ad ad) {
  ...
  List<View> clickableViews = new ArrayList<>();
  clickableViews.add(nativeAdTitle);
  clickableViews.add(nativeAdCallToAction);
  nativeBannerAd.registerViewForInteraction(mAdView, nativeAdIconView, clickableViews);
  ...
}

시간이 지난 후 이 보기를 다시 사용하여 다른 광고를 표시할 경우, unregisterView()를 호출한 후 NativeBannerAd의 다른 인스턴스로 동일한 보기를 등록해야 합니다.

코드를 실행하면 네이티브 배너 광고가 보일 것입니다.

광고를 읽어들이면 다음 속성에 title, icon, callToAction 등의 값이 포함됩니다. 다른 속성은 null이거나 비어 있을 수 있습니다. 이러한 사례를 처리할 수 있도록 코드를 안정화하세요.


표시할 광고가 없을 경우 error.code와 함께 onError가 호출됩니다. 자체 맞춤 설정 보고 또는 미디에이션 레이어를 사용할 경우, 코드 값을 검사하고 이 사례를 탐지하는 것이 좋습니다. 이 경우에는 다른 광고 네트워크로 폴백해도 되지만 그 직후에 광고 요청을 다시 전송하지 마세요.


수신하는 광고 메타데이터는 캐시하여 최대 30분 동안 다시 사용할 수 있습니다. 이 시간이 지난 후 메타데이터를 사용하려면 새 광고를 읽어들이기 위한 호출을 보내야 합니다.

다음 단계

  • 앱에 네이티브 광고를 추가하려면 네이티브 광고 템플릿 가이드를 참조하세요.

  • 네이티브 광고 사용법을 보여주는 코드 샘플을 참조하세요. NativeBannerAdSample은 SDK의 AudienceNetwork/samples 폴더에서 확인할 수 있습니다. IDE로 프로젝트를 가져와서 기기나 에뮬레이터에서 실행하세요.

기타 참고 자료

시작하기 가이드

Audience Network를 시작하기 위한 기술 가이드

코드 샘플

Audience Network 광고 통합 샘플

FAQ

Audience Network FAQ

네이티브 광고 템플릿

네이티브 광고를 통합하는 더욱 간편한 방법