Dokumen ini sudah diperbarui.
Terjemahan ke Bahasa Indonesia belum selesai.
Bahasa Inggris diperbarui: 21 Des 2021
Bahasa Indonesia diperbarui: 1 Mar 2019

Add Native Ads to an Android App

The Native Ad API allows you to build a customized experience for the ads you show in your app. When using the Native Ad API, instead of receiving an ad ready to be displayed, you will receive a group of ad properties such as a title, an image, a call to action, and you will have to use them to construct a custom view where the ad is shown.

Pastikan Anda sudah membaca tuntas panduan Memulai dan Memulai Android Audience Network sebelum melanjutkan.

In this guide we will implement the following native ad placement. You will create a native ad with the following components:

View #1: Ad Icon

View #2: Ad Title

View #3: Sponsored Label

View #4: AdOptionsView

View #5: MediaView

View #6: Social Context

View #7: Ad Body

View #8: Call to Action button




Native Ad Steps

Step 1: Requesting a Native Ad

Step 2: Creating your Native Ad Layout

Step 3: Populating your Layout Using the Ad's Metadata

Step 4: Using MediaView

Setp 5: Load Ad without Auto Cache

Menginisialisasi SDK Audience Network

Metode ini ditambahkan di SDK Audience Network Android versi 5.1.

Inisialisasi eksplisit SDK Audience Network Android diperlukan untuk versi 5.3.0 dan lebih besar. Baca dokumen ini tentang cara menginisialisasi SDK Audience Network Android.

Sebelum membuat benda iklan dan memuat iklan, Anda harus menginisialisasi SDK Audience Network. Sebaiknya lakukan hal ini pada saat aplikasi dibuka.

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

Step 1: Requesting a Native Ad

Add the following code at the top of your Activity to import the Facebook Ads SDK:

import com.facebook.ads.*;

Then, instantiate a NativeAd object, create a NativeAdListener, and call loadAd() with the ad listener:

private final String TAG = "NativeAdActivity".getClass().getSimpleName();
private NativeAd nativeAd;

private void loadNativeAd() {
    // Instantiate a NativeAd 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).
    nativeAd = new NativeAd(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!");
        }
    };

    // Request an ad
    nativeAd.loadAd(
            nativeAd.buildLoadAdConfig()
                    .withAdListener(nativeAdListener)
                    .build());
}

We will be coming back later to add code to the onAdLoaded() method.

Step 2: Creating your Native Ad Layout

The next step is to extract the ad metadata and use its properties to build your customized native UI. You can either create your custom view in a layout .xml, or you can add elements in code.

Please consult our guidelines for native ads when designing native ads in your app.

In your Activity's layout activity_main.xml, add a container for your Native Ad. The container should be a com.facebook.ads.NativeAdLayout which is a wrapper on top of a FrameLayout with some extra functionality that enabled us to render a native Ad Reporting Flow on top of the ad.

<?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"
    android:gravity="center_horizontal"
    android:paddingTop="50dp">
    ...
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="50dp">

        <com.facebook.ads.NativeAdLayout
             android:id="@+id/native_ad_container"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:orientation="vertical" />
     </ScrollView>
    ...
</RelativeLayout>

Create a custom layout native_ad_layout.xml for your native ad:



Below is an example custom layout for your Native Ad:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ad_unit"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:orientation="vertical"
    android:paddingLeft="10dp"
    android:paddingRight="10dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingBottom="10dp"
        android:paddingTop="10dp">

        <com.facebook.ads.MediaView
            android:id="@+id/native_ad_icon"
            android:layout_width="35dp"
            android:layout_height="35dp" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingLeft="5dp"
            android:paddingRight="5dp">

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

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

    </LinearLayout>

    <LinearLayout
        android:id="@+id/ad_choices_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="end"
        android:orientation="horizontal" />

    </LinearLayout>

    <com.facebook.ads.MediaView
        android:id="@+id/native_ad_media"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />

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

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:orientation="vertical">

            <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:textColor="@android:color/darker_gray"
                android:textSize="12sp" />

            <TextView
                android:id="@+id/native_ad_body"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:gravity="center_vertical"
                android:lines="2"
                android:textColor="@android:color/black"
                android:textSize="12sp" />

        </LinearLayout>

        <Button
            android:id="@+id/native_ad_call_to_action"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:background="#4286F4"
            android:paddingLeft="3dp"
            android:paddingRight="3dp"
            android:textColor="@android:color/white"
            android:textSize="12sp"
            android:visibility="gone" />

    </LinearLayout>

</LinearLayout>

Step 3: Populating your Layout Using the Ad's Metadata

Scenario 1: Immediately display the ad once it is loaded successfully. Modify the onAdLoaded() method above to retrieve the Native Ad's properties and display it as follows:

private NativeAdLayout nativeAdLayout;
private LinearLayout adView;
private NativeAd nativeAd;

private void loadNativeAd() {
    // Instantiate a NativeAd 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).
    nativeAd = new NativeAd(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 (nativeAd == null || nativeAd != ad) {
                return;
            }
            // Inflate Native Ad into Container
            inflateAd(nativeAd);
        }
        ...
    };

    // Request an ad
    nativeAd.loadAd(
            nativeAd.buildLoadAdConfig()
                    .withAdListener(nativeAdListener)
                    .build());
}

private void inflateAd(NativeAd nativeAd) {

    nativeAd.unregisterView();

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

    // Add the AdOptionsView
    LinearLayout adChoicesContainer = findViewById(R.id.ad_choices_container);
    AdOptionsView adOptionsView = new AdOptionsView(NativeAdActivity.this, nativeAd, nativeAdLayout);
    adChoicesContainer.removeAllViews();
    adChoicesContainer.addView(adOptionsView, 0);

    // Create native UI using the ad metadata.
    MediaView nativeAdIcon = adView.findViewById(R.id.native_ad_icon);
    TextView nativeAdTitle = adView.findViewById(R.id.native_ad_title);
    MediaView nativeAdMedia = adView.findViewById(R.id.native_ad_media);
    TextView nativeAdSocialContext = adView.findViewById(R.id.native_ad_social_context);
    TextView nativeAdBody = adView.findViewById(R.id.native_ad_body);
    TextView sponsoredLabel = adView.findViewById(R.id.native_ad_sponsored_label);
    Button nativeAdCallToAction = adView.findViewById(R.id.native_ad_call_to_action);

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

    // Create a list of clickable views
    List<View> clickableViews = new ArrayList<>();
    clickableViews.add(nativeAdTitle);
    clickableViews.add(nativeAdCallToAction);

    // Register the Title and CTA button to listen for clicks.
    nativeAd.registerViewForInteraction(
            adView, nativeAdMedia, nativeAdIcon, clickableViews);
}

The SDK will log the impression and handle the click automatically. Please note that you must register the ad's view with the NativeAd instance to enable that. To make all ad elements of the view clickable register it using:

registerViewForInteraction(View view, MediaView adMediaView, MediaView adIconView)

When using registerViewForInteraction with NativeAds, the SDK checks that the call is running on the Main Thread, to avoid race conditions. We perform our check using Preconditions.checkIsOnMainThread(). Please ensure that your implementation conforms to this standard as your app will crash if you try to call registerViewForInteraction from a Background Thread.

Scenario 2: Display the ad in a few seconds or minutes after it is successfully loaded. You should check whether the ad has been invalidated before displaying it.

Jika iklan tidak segera ditampilkan setelah termuat, developer bertanggung jawab untuk memastikan apakah iklan tersebut masih valid atau tidak. Setelah iklan berhasil dimuat, iklan akan valid selama 60 menit. Anda tidak akan dibayar jika menampilkan iklan yang tidak lagi valid. Anda sebaiknya memanggil isAdInvalidated() untuk memvalidasi iklan.

You should follow the idea below, but please do not copy the code into your project since it is just an example:

private NativeAd nativeAd;

private void loadNativeAd() {
    // Instantiate a NativeAd 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).
    nativeAd = new NativeAd(this, "YOUR_PLACEMENT_ID");

    NativeAdListener nativeAdListener = new NativeAdListener() {
        ...
    };

    // Request an ad
    nativeAd.loadAd(
            nativeAd.buildLoadAdConfig()
                    .withAdListener(nativeAdListener)
                    .build());

    // Here is just an example for displaying the ad with delay
    // Please call this method at appropriate timing in your project
    showNativeAdWithDelay();
}

private void showNativeAdWithDelay() {
    /**
     * 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 nativeAd has been loaded successfully
            if(nativeAd == null || !nativeAd.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(nativeAd.isAdInvalidated()) {
                return;
            }
            inflateAd(nativeAd); // Inflate NativeAd into a container, same as in previous code examples
        }
    }, 1000 * 60 * 15); // Show the ad after 15 minutes
}

Controlling Clickable Area

Untuk pengalaman pengguna dan hasil yang lebih baik, Anda harus selalu mempertimbangkan mengontrol area yang dapat diklik pada iklan Anda untuk menghindari klik yang tidak diinginkan. Silakan melihat halaman Kebijakan SDK Audience Network untuk detail selengkapnya tentang penegakan ruang putih yang tidak dapat diklik.

For finer control of what is clickable, you can use the registerViewForInteraction(View view, MediaView adMediaView, MediaView adIconView, List<View> clickableViews) to register a list of views that can be clicked. For example, if we only want to make the ad title and the call-to-action button clickable in the previous example, you can write it like this:

@Override
public void onAdLoaded(Ad ad) {
    ...
    // Create a list of clickable views
    List<View> clickableViews = new ArrayList<>();
    clickableViews.add(nativeAdTitle);
    clickableViews.add(nativeAdCallToAction);

    // Register the Title and CTA button to listen for clicks.
    nativeAd.registerViewForInteraction(
            adView, nativeAdMedia, nativeAdIcon, clickableViews);
    ...
}

In cases where you reuse the view to show different ads over time, make sure to call unregisterView() before registering the same view with a different instance of NativeAd.

Run the code and you should see a Native Ad:

Step 4: Using MediaView

For displaying the native ad cover image, it is mandatory to use the Meta Audience Network MediaView which can display both image and video assets. You can review our design guidelines for native video ad units here.

By default, image and video assets are all pre-cached when loading native ads, which enables the MediaView to play videos immediately after nativeAd finishes loading.

private void loadNativeAd() {
    ...
    nativeAd.loadAd();
}

Also, you can explicitly specify NativeAd.MediaCacheFlag.ALL when loading native ads.

private void loadNativeAd() {
    ...
    nativeAd.loadAd(
            nativeAd.buildLoadAdConfig()
                    .withMediaCacheFlag(NativeAdBase.MediaCacheFlag.ALL)
                    .build());
}

Audience Network supports two cache options in native ads as defined in the NativeAd.MediaCacheFlag enum:

Cache Constants Description

ALL

Pre-cache all (icon, images, and video), default

NONE

No pre-caching

When an ad is loaded, the following properties will include some value: title, icon, coverImage and callToAction. Other properties might be null or empty. Make sure your code is robust enough to handle these cases.

When there is no ad to show, onError will be called with an error.code. If you use your own custom reporting or mediation layer you might want to check the code value and detect this case. You can fallback to another ad network in this case, but do not re-request an ad immediately after.

Ad metadata that you receive can be cached and re-used for up to 1 hour. If you plan to use the metadata after this time period, make a call to load a new ad.

Step 5: Load Ad without Auto Cache

  • We strongly recommend to leave media caching on by default in all cases. However, we allow you to override the default by using the MediaCacheFlag.NONE in the loadAd method. Please be very careful if you decide to override our default media caching.
private final String TAG = NativeAdActivity.class.getSimpleName();
private NativeAd nativeAd;

private void loadNativeAd() {
    // Instantiate a NativeAd 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).
    nativeAd = new NativeAd(this, "YOUR_PLACEMENT_ID");
    NativeAdListener nativeAdListener = new NativeAdListener() {
        ...
    };

    // Request an ad without auto cache
    nativeAd.loadAd(
            nativeAd.buildLoadAdConfig()
                    .withAdListener(nativeAdListener)
                    .withMediaCacheFlag(NativeAdBase.MediaCacheFlag.NONE)
                    .build());
}
  • After the onAdLoaded is successfully invoked on your ad, you can manually call the downloadMedia method to start downloading all media for the native ad when appropriate.
@Override
public void onAdLoaded(Ad ad) {
    if (nativeAd == null || nativeAd != ad) {
        return;
    }

    nativeAd.downloadMedia();
}
  • Finally, you can call registerViewForInteraction method and display the ad when the media finished loading in the onMediaDownloaded callback.
@Override
public void onMediaDownloaded(Ad ad) {
    if (nativeAd == null || nativeAd != ad) {
        return;
    }

    inflateAd(nativeAd); // Inflate NativeAd into a container, same as in previous code examples
}

If you loaded the ad without auto cache and didn't manually call downloadMedia to start the download, the media will only start to be downloaded when registerViewForInteraction is called. All media need to be loaded and displayed for an eligible impression.

Akselerasi Perangkat Keras untuk Iklan Video

Untuk mengaktifkan iklan video di Audience Network diperlukan render yang diakselerasi perangkat keras, jika tidak ada maka layar mungkin akan menjadi hitam di tayangan video. Ini berlaku untuk

  • Materi iklan video di Iklan Native
  • Materi iklan video di Interstisial
  • Iklan Video In-stream
  • Video yang Mendapatkan Hadiah

Akselerasi perangkat keras diaktifkan secara default jika level API Target adalah >=14 (Ice Cream Sandwich, Android 4.0.1), namun Anda juga dapat secara eksplisit menyalakan fitur ini pada level aplikasi atau level aktivitas.

Level Aplikasi

Di file manifes Android, tambahkan atribut berikut ke tag <application> untuk mengaktifkan percepatan perangkat keras untuk seluruh aplikasi Anda:

<application android:hardwareAccelerated="true" ...>

Level Aktivitas

Jika Anda hanya ingin mengaktifkan fitur untuk aktivitas tertentu di aplikasi, dalam file manifes Android, Anda dapat menambahkan fitur berikut ke tag <activity>. Contoh berikut akan mengaktifkan percepatan perangkat keras untuk AudienceNetworkActivity yang digunakan untuk rendering iklan pengantara dan video hadiah:

<activity android:name="com.facebook.ads.AudienceNetworkActivity" android:hardwareAccelerated="true" .../>

Next Steps

  • See the Native Ad Template guide to add native ads in your app.

  • Explore our code samples which demonstrate how to use native ads. The NativeAdSample is available as part of the SDK and can be found under the AudienceNetwork/samples folder. Import the project to your IDE and run it either on a device or the emulator.

More Resources

Getting Started Guide

Technical guide to get started with Audience Network

Code Samples

Audience Network Ads Integration Samples

FAQ

Audience Network FAQ

Native Ads Template

A more hands off approach when integrating Native Ads