Facebook Audience Network

random

Initialize the Audience Network SDK

This method was added in the Android Audience Network SDK version 5.1.
Before creating an ad object and loading ads, you should initialize the Audience Network SDK. It is recommended to do this at app launch.
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, set an AdListener, and call loadAd():
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");

nativeAd
.setAdListener(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();
}
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.AdIconView
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");

nativeAd
.setAdListener(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();
}

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.
AdIconView 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, AdIconView 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.

In case of not showing the ad immediately after the ad has been loaded, the developer is responsible for checking whether or not the ad has been invalidated. Once the ad is successfully loaded, the ad will be valid for 60 mins. You will not get paid if you are showing an invalidated ad. You should call isAdInvalidated() to validate the ad.
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");

nativeAd
.setAdListener(new NativeAdListener() {
...
});

// Request an ad
nativeAd
.loadAd();

// 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 Native Ad into Container same as previous code example
}
}, 1000 * 60 * 15); // Show the ad after 15 minutes
}

Controlling Clickable Area

For a better user experience and better results, you should always consider controlling the clickable area of your ad to avoid unintentional clicks. Please refer to Audience Network SDK Policy page for more details about white space unclickable enforcement.
For finer control of what is clickable, you can use the registerViewForInteraction(View view, MediaView adMediaView, AdIconView 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 Facebook 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.MediaCacheFlag.ALL);
}
Audience Network supports two cache options in native ads as defined in the NativeAd.MediaCacheFlag enum:
Cache ConstantsDescription
ALLPre-cache all (icon, images, and video), default
NONENo pre-caching
When an ad is loaded, the following properties will include some value: titleiconcoverImage 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");
nativeAd
.setAdListener(new NativeAdListener() {
...
});

// Request an ad without auto cache
nativeAd
.loadAd(NativeAdBase.MediaCacheFlag.NONE);
}
  • 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);
}
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.

Hardware Acceleration for Video Ads

Videos ads in Audience Network requires the hardware accelerated rendering to be enabled, otherwise you might experience a black screen in the video views. This applies to
  • Videos creatives in Native Ads
  • Videos creatives in Interstitials
  • In-stream Video ads
  • Rewarded Videos
Hardware acceleration is enabled by default if your Target API level is >=14 (Ice Cream Sandwich, Android 4.0.1), but you can also explicitly enable this feature at the application level or activity level.

Application Level

In your Android manifest file, add the following attribute to the <application> tag to enable hardware acceleration for your entire application:
<application android:hardwareAccelerated="true" ...>

Activity Level

If you only want to enable the feature for specific activities in your application, in your Android manifest file, you can add the following feature to the <activity> tag. The following example will enable the hardware acceleration for the AudienceNetworkActivity which is used for rendering interstitial ads and rewarded videos:
<activity android:name="com.facebook.ads.AudienceNetworkActivity" android:hardwareAccelerated="true" .../>
Reviewed by Code Labe on April 21, 2019 Rating: 5

Contact Form

Name

Email *

Message *

Powered by Blogger.