Native ads in android

Содержание
  1. Native Ads
  2. Prerequisites
  3. Load an Ad
  4. Build an AdLoader
  5. Kotlin
  6. Prepare for the NativeAd format
  7. Use AdListener with an AdLoader
  8. Kotlin
  9. Loading ads
  10. Kotlin
  11. Kotlin
  12. Kotlin
  13. Cleaning up
  14. Kotlin
  15. Always test with test ads
  16. When to request ads
  17. Hardware acceleration for video ads
  18. Enabling hardware acceleration
  19. Display a NativeAd
  20. Native Ads
  21. Prerequisites
  22. Load an Ad
  23. Build an AdLoader
  24. Kotlin
  25. Prepare for the NativeAd format
  26. Use AdListener with an AdLoader
  27. Kotlin
  28. Loading ads
  29. Kotlin
  30. Kotlin
  31. Kotlin
  32. Cleaning up
  33. Kotlin
  34. Always test with test ads
  35. When to request ads
  36. Hardware acceleration for video ads
  37. Enabling hardware acceleration
  38. Display a NativeAd
  39. Add Native Ads to an Android App
  40. View #1: Ad Icon
  41. View #2: Ad Title
  42. View #3: Sponsored Label
  43. View #4: AdOptionsView
  44. View #5: MediaView
  45. View #6: Social Context
  46. View #7: Ad Body
  47. View #8: Call to Action button
  48. Native Ad Steps
  49. Step 1: Requesting a Native Ad
  50. Step 2: Creating your Native Ad Layout
  51. Step 3: Populating your Layout Using the Ad’s Metadata
  52. Step 4: Using MediaView
  53. Setp 5: Load Ad without Auto Cache
  54. Инициализация SDK Audience Network
  55. Step 1: Requesting a Native Ad
  56. Step 2: Creating your Native Ad Layout
  57. Step 3: Populating your Layout Using the Ad’s Metadata
  58. 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:
  59. 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.
  60. Controlling Clickable Area
  61. Step 4: Using MediaView
  62. Step 5: Load Ad without Auto Cache
  63. Аппаратное ускорение для видеорекламы
  64. Уровень приложения
  65. Уровень действий
  66. Next Steps
  67. More Resources
  68. Getting Started Guide
  69. Code Samples
  70. Native Ads Template

Native Ads

Native ads are ad assets that are presented to users via UI components that are native to the platform. They’re shown using the same types of views with which you’re already building your layouts, and can be formatted to match the visual design of the user experience in which they live. In coding terms, this means that when a native ad loads, your app receives a NativeAd object that contains its assets, and the app (rather than the Google Mobile Ads SDK) is then responsible for displaying them.

Broadly speaking, there are two parts to successfully implementing Native Ads: loading an ad via the SDK and displaying the ad content in your app. This page is concerned with using the SDK to load native ads.

Prerequisites

  • Import the Google Mobile Ads SDK, either by itself or as part of Firebase.

Load an Ad

Native ads are loaded via the AdLoader class, which has its own Builder class to customize it during creation. By adding listeners to the AdLoader while building it, an app specifies which types of native ads it is ready to receive. The AdLoader then requests just those types.

Build an AdLoader

The following code demonstrates how to build an AdLoader that can load native ads:

Kotlin

Prepare for the NativeAd format

The first method above is responsible for preparing the AdLoader for the NativeAd format:

forNativeAd() Calling this method configures the AdLoader to request native ads. When an ad has loaded successfully, the listener object’s onNativeAdLoaded() method is called.

When the AdLoader makes an ad request, Google selects and returns the ad that maximizes publisher yield.

Use AdListener with an AdLoader

During creation of the AdLoader above, the withAdListener function sets an AdListener .

This is an optional step. The method takes an AdListener as its lone parameter, which receives callbacks from the AdLoader when ad lifecycle events take place:

Kotlin

Loading ads

Once you’ve finished building an AdLoader , it’s time to use it to load ads. There are two methods available for this: loadAd() and loadAds() .

The loadAd() method sends a request for a single ad:

loadAd() This method sends a request for a single ad.

Kotlin

The loadAds() method sends a request for multiple ads (up to 5):

Kotlin

Both of these methods take a AdRequest object as their first parameter. This is the same AdRequest class used by banners and interstitials, and you can use methods of the AdRequest class to add targeting information, just as you would with other ad formats.

loadAds() takes an additional parameter: the number of ads the SDK should attempt to load for the request. This number is capped at a maximum of five, and it’s not guaranteed that the SDK will return the exact number of ads requested. If multiple ads are returned by a call to loadAds() , they will be different from each other.

After a call to loadAd() , a single callback will be made to the listener methods defined above to deliver the native ad object or report an error.

After a call to loadAds() , multiple such callbacks will be made (at least one, and no more than the number of ads requested). Apps requesting multiple ads should call AdLoader.isLoading() in their callback implementations to determine whether the loading process has finished.

Here’s an example showing how to check isLoading() in the onNativeAdLoaded() callback:

Kotlin

Cleaning up

Be sure to use the destroy() method on loaded native ads. This frees up utilized resources and prevents memory leaks.

Ensure that all NativeAd references are destroyed in your activity’s onDestroy() method.

In your onNativeAdLoaded callback, make sure to destroy any existing native ads that will be dereferenced.

Another key check is if the activity is destroyed and if so, call destroy() on the returned ad and return immediately:

Kotlin

Always test with test ads

When building and testing your apps, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account.

Читайте также:  Gpu ускорение андроид что это нужно ли включать

The easiest way to load test ads is to use our dedicated test ad unit ID for Native Advanced on Android:

It’s been specially configured to return test ads for every request, and you’re free to use it in your own apps while coding, testing, and debugging. Just make sure you replace it with your own ad unit ID before publishing your app.

For more information about how the Mobile Ads SDK’s test ads work, see Test Ads.

When to request ads

Applications displaying native ads are free to request them in advance of when they’ll actually be displayed. In many cases, this is the recommended practice. An app displaying a list of items with native ads mixed in, for example, can load native ads for the whole list, knowing that some will be shown only after the user scrolls the view and some may not be displayed at all.

Hardware acceleration for video ads

In order for video ads to show successfully in your native ad views, hardware acceleration must be enabled.

Hardware acceleration is enabled by default, but some apps may choose to disable it. If this applies to your app, we recommend enabling hardware acceleration for Activity classes that use ads.

Enabling hardware acceleration

If your app does not behave properly with hardware acceleration turned on globally, you can control it for individual activities as well. To enable or disable hardware acceleration, you can use the android:hardwareAccelerated attribute for the and elements in your AndroidManifest.xml . The following example enables hardware acceleration for the entire app but disables it for one activity:

See the HW acceleration guide for more information about options for controlling hardware acceleration. Note that individual ad views cannot be enabled for hardware acceleration if the Activity is disabled, so the Activity itself must have hardware acceleration enabled.

Display a NativeAd

Once you have loaded an ad, all that remains is to display it to your users. Head over to our Native Advanced guide to see how.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Native Ads

Native ads are ad assets that are presented to users via UI components that are native to the platform. They’re shown using the same types of views with which you’re already building your layouts, and can be formatted to match the visual design of the user experience in which they live. In coding terms, this means that when a native ad loads, your app receives a NativeAd object that contains its assets, and the app (rather than the Google Mobile Ads SDK) is then responsible for displaying them.

Broadly speaking, there are two parts to successfully implementing Native Ads: loading an ad via the SDK and displaying the ad content in your app. This page is concerned with using the SDK to load native ads.

Prerequisites

  • Import the Google Mobile Ads SDK, either by itself or as part of Firebase.

Load an Ad

Native ads are loaded via the AdLoader class, which has its own Builder class to customize it during creation. By adding listeners to the AdLoader while building it, an app specifies which types of native ads it is ready to receive. The AdLoader then requests just those types.

Build an AdLoader

The following code demonstrates how to build an AdLoader that can load native ads:

Kotlin

Prepare for the NativeAd format

The first method above is responsible for preparing the AdLoader for the NativeAd format:

forNativeAd() Calling this method configures the AdLoader to request native ads. When an ad has loaded successfully, the listener object’s onNativeAdLoaded() method is called.

When the AdLoader makes an ad request, Google selects and returns the ad that maximizes publisher yield.

Use AdListener with an AdLoader

During creation of the AdLoader above, the withAdListener function sets an AdListener .

This is an optional step. The method takes an AdListener as its lone parameter, which receives callbacks from the AdLoader when ad lifecycle events take place:

Kotlin

Loading ads

Once you’ve finished building an AdLoader , it’s time to use it to load ads. There are two methods available for this: loadAd() and loadAds() .

The loadAd() method sends a request for a single ad:

loadAd() This method sends a request for a single ad.

Kotlin

The loadAds() method sends a request for multiple ads (up to 5):

Kotlin

Both of these methods take a AdRequest object as their first parameter. This is the same AdRequest class used by banners and interstitials, and you can use methods of the AdRequest class to add targeting information, just as you would with other ad formats.

loadAds() takes an additional parameter: the number of ads the SDK should attempt to load for the request. This number is capped at a maximum of five, and it’s not guaranteed that the SDK will return the exact number of ads requested. If multiple ads are returned by a call to loadAds() , they will be different from each other.

After a call to loadAd() , a single callback will be made to the listener methods defined above to deliver the native ad object or report an error.

After a call to loadAds() , multiple such callbacks will be made (at least one, and no more than the number of ads requested). Apps requesting multiple ads should call AdLoader.isLoading() in their callback implementations to determine whether the loading process has finished.

Читайте также:  Как обновить зеркало андроид

Here’s an example showing how to check isLoading() in the onNativeAdLoaded() callback:

Kotlin

Cleaning up

Be sure to use the destroy() method on loaded native ads. This frees up utilized resources and prevents memory leaks.

Ensure that all NativeAd references are destroyed in your activity’s onDestroy() method.

In your onNativeAdLoaded callback, make sure to destroy any existing native ads that will be dereferenced.

Another key check is if the activity is destroyed and if so, call destroy() on the returned ad and return immediately:

Kotlin

Always test with test ads

When building and testing your apps, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account.

The easiest way to load test ads is to use our dedicated test ad unit ID for Native Advanced on Android:

It’s been specially configured to return test ads for every request, and you’re free to use it in your own apps while coding, testing, and debugging. Just make sure you replace it with your own ad unit ID before publishing your app.

For more information about how the Mobile Ads SDK’s test ads work, see Test Ads.

When to request ads

Applications displaying native ads are free to request them in advance of when they’ll actually be displayed. In many cases, this is the recommended practice. An app displaying a list of items with native ads mixed in, for example, can load native ads for the whole list, knowing that some will be shown only after the user scrolls the view and some may not be displayed at all.

Hardware acceleration for video ads

In order for video ads to show successfully in your native ad views, hardware acceleration must be enabled.

Hardware acceleration is enabled by default, but some apps may choose to disable it. If this applies to your app, we recommend enabling hardware acceleration for Activity classes that use ads.

Enabling hardware acceleration

If your app does not behave properly with hardware acceleration turned on globally, you can control it for individual activities as well. To enable or disable hardware acceleration, you can use the android:hardwareAccelerated attribute for the and elements in your AndroidManifest.xml . The following example enables hardware acceleration for the entire app but disables it for one activity:

See the HW acceleration guide for more information about options for controlling hardware acceleration. Note that individual ad views cannot be enabled for hardware acceleration if the Activity is disabled, so the Activity itself must have hardware acceleration enabled.

Display a NativeAd

Once you have loaded an ad, all that remains is to display it to your users. Head over to our Native Advanced guide to see how.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

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.

Прежде чем продолжить, обязательно ознакомьтесь с руководствами по началу работы с Audience Network и Android.

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

Инициализация SDK Audience Network

Этот метод добавлен в SDK Audience Network 5.1 для Android.

Начиная с версии 5.3.0 явная инициализация SDK Audience Network для Android обязательна. Информацию о том, как инициализировать SDK Audience Network для Android, см. в этом документе.

Чтобы создавать рекламные объекты и загружать рекламу, необходимо инициализировать SDK Audience Network. Рекомендуется сделать это при запуске приложения.

Step 1: Requesting a Native Ad

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

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

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.

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

Below is an example custom layout for your Native Ad:

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:

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:

Читайте также:  Часы связанные с телефоном андроид

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.

Если сразу же после загрузки рекламное объявление не показывается, разработчик должен проверить, не стала ли реклама недействительной. После успешной загрузки реклама остается действительной в течение 60 минут. Показ недействительной рекламы не оплачивается. Чтобы проверить рекламу, вызовите метод isAdInvalidated() .

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

Controlling Clickable Area

Если вы хотите сделать свою рекламу удобной для пользователей и результативной, всегда старайтесь настроить интерактивную область так, чтобы пользователи не нажимали на нее по ошибке. Подробнее о правилах в отношении некликабельного свободного пространства см. на странице Политика Facebook Audience Network.

For finer control of what is clickable, you can use the registerViewForInteraction(View view, MediaView adMediaView, MediaView adIconView, List 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:

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.

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

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

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

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.
  • 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.
  • Finally, you can call registerViewForInteraction method and display the ad when the media finished loading in the onMediaDownloaded callback.

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.

Аппаратное ускорение для видеорекламы

Для показа видеорекламы в Audience Network необходимо включить обработку с аппаратным ускорением, иначе видео могут не отображаться должным образом. Это касается:

Аппаратное ускорение включено по умолчанию, если уровень API Target будет не менее 14 (Ice Cream Sandwich, Android 4.0.1), но помимо этого вы можете напрямую включить эту функцию на уровне приложения или действий.

Уровень приложения

Чтобы включить аппаратное ускорение для всего приложения, в файле манифеста Android добавьте следующий атрибут в тег :

Уровень действий

Если вы хотите включить эту функцию только для определенных действий в приложении, в файле манифеста Android добавьте следующую функцию в тег . В примере ниже аппаратное ускорение включено для действия AudienceNetworkActivity , которое используется для обработки рекламных вставок и видео с бонусами.

Next Steps

Relevant code samples in both Swift and Objective-C are available on our GitHub sample app respository

As soon as we receive a request for an ad from your app or website, we’ll review it to make sure it complies with Audience Network policies and the Facebook community standards

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

Audience Network FAQ

Native Ads Template

A more hands off approach when integrating Native Ads

Источник

Оцените статью