Android banner from top

Banner ads are classic static banners, which are usually located at the bottom or top of the advertisement.

Appodeal supports traditional 320×50 banners, tablet banners 728×90 and smart banners that adjust to the size and orientation of the device.

You can display only one view for banner on the screen.

1. Display banner at the specific position of the screen

SDK can’t show ads without a network connection!

Appodeal.show() returns a boolean value indicating whether the show method call was passed to the appropriate SDK.

2. Display banner in the specified view in the layout file

Add com.appodeal.ads.BannerView to your layout file:

3. Display banner in programmatically created view

Create banner view:

4. Check if a banner is loaded

5. Use banner callbacks

6. Activity «Paused» state handling

We’ll automatically handle pause and resume state for already displayed Banners on Activity on which they were displayed, however, we don’t restore displayed Banners after Activity recreation (e.g. — orientation changes) and we don’t show Banners in newly created Activities.
For display ads on newly created Activity just call Appodea.show() method if required.

This behavior can be changed by calling Appodeal.setSharedAdsInstanceAcrossActivities(true)
(See more: Enable Shared View Ads Instance Across Activities Logic )

7. Hide banner

8. Destroy shown banner

If you want to hide the banner from all activities and clear the memory, call the code below:

9. Cache banner manually

To disable automatic caching for banners, use the code below before the SDK initialization:

10. Configuration

10.1. Enable 728*90 banners

To enable 728*90 banners, use the following method:

10.2. Disable banner refresh animation

To disable banner refresh animation, use:

10.3. Disable smart banners

Smart banners are the banner ads that automatically fit the screen size. Using them helps to deal with the increasing fragmentation of the screen sizes on different devices. In the Appodeal SDK, the smart banners are enabled by default. To disable them, use the following method:

11. Check if the banner was initialized

To check if banner was initialized, you can use the method:

12. Check if autocache is enabled for banner

To check if autocache is enabled for banner, you can use the method:

13. Get predicted eCPM for banner

To get the predicted eCPM from the next block in the caching queue, use the method:

This method is reasonable to use if manual caching of ads is enabled.

14. Enable Shared View Ads Instance Across Activities Logic

Starting from SDK 2.8.1 Appodeal SDK binds the Banner/MREC to the Activity which was passed to the Appodeal.show method.

To make it easier for you to manage View ads display logic across all Activities w e added a new method in Appodeal class:

  • When this method is used with the true parameter, the SDK will show AdView on all new activities w ithout calling additional code from your side.
  • If you want to control the display yourself, you can call the method with the false parameter.

In this case, this parameter is false , b e careful with changing orientation or moving to a new activity, the banner/MREC will not be shown automatically, since it was bound to the previous activity.
If you want to hide the banner/MREC, you need to call the Appodeal.hide() method with the parameters of the activity to which the banner/MREC was bound.

Читайте также:  Что круче эпл или андроид

You can also check the current state of this logic. By default value is false :

Источник

Banner ads occupy a spot within an app’s layout, either at the top or bottom of the device screen. They stay on screen while users are interacting with the app, and can refresh automatically after a certain period of time. If you’re new to mobile advertising, they’re a great place to start. Case study.

This guide shows you how to integrate banner ads from AdMob into an Android app. In addition to code snippets and instructions, it also includes information about sizing banners properly and links to additional resources.

Prerequisites

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

Add AdView to the layout

The first step toward displaying a banner is to place AdView in the layout for the Activity or Fragment in which you’d like to display it. The easiest way to do this is to add one to the corresponding XML layout file. Here’s an example that shows an activity’s AdView :

Note the following required attributes:

  • ads:adSize — Set this to the ad size you’d like to use. If you don’t want to use the standard size defined by the constant, you can set a custom size instead. See the banner size section below for details.
  • ads:adUnitId — Set this to the unique identifier given to the ad unit in your app where ads are to be displayed. If you show banner ads in different activities, each would require an ad unit.

You can alternatively create AdView programmatically:

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 Android banners:

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.

Load an ad

Once the AdView is in place, the next step is to load an ad. That’s done with the loadAd() method in the AdView class. It takes an AdRequest parameter, which holds runtime information (such as targeting info) about a single ad request.

Here’s an example that shows how to load an ad in the onCreate() method of an Activity :

MainActivity (excerpt)

Kotlin

That’s it! Your app is now ready to display banner ads.

Ad events

To further customize the behavior of your ad, you can hook onto a number of events in the ad’s lifecycle: loading, opening, closing, and so on. You can listen for these events through the AdListener class.

To use an AdListener with AdView , call the setAdListener() method:

Kotlin

Each of the overridable methods in AdListener corresponds to an event in the lifecycle of an ad.

Overridable methods
onAdLoaded() The onAdLoaded() method is executed when an ad has finished loading. If you want to delay adding the AdView to your activity or fragment until you’re sure an ad will be loaded, for example, you can do so here.
onAdFailedToLoad() The onAdFailedToLoad() method is the only one that includes a parameter. The error parameter of type LoadAdError describes what error occurred. For more information, refer to the Debugging Ad Load Errors documentation.
onAdOpened() This method is invoked when the user taps on an ad.
onAdClosed() When a user returns to the app after viewing an ad’s destination URL, this method is invoked. Your app can use it to resume suspended activities or perform any other work necessary to make itself ready for interaction. Refer to the AdMob AdListener example for an implementation of the ad listener methods in the Android API Demo app.

The table below lists the standard banner sizes.

Size in dp (WxH) Description Availability AdSize constant
320×50 Banner Phones and Tablets BANNER
320×100 Large Banner Phones and Tablets LARGE_BANNER
300×250 IAB Medium Rectangle Phones and Tablets MEDIUM_RECTANGLE
468×60 IAB Full-Size Banner Tablets FULL_BANNER
728×90 IAB Leaderboard Tablets LEADERBOARD
Provided width x Adaptive height Adaptive banner Phones and Tablets N/A
Screen width x 32|50|90 Smart banner Phones and Tablets SMART_BANNER
Learn more about Adaptive Banners, intended to replace Smart Banners.
Читайте также:  The dude для android

To define a custom banner size, set your desired AdSize , as shown here:

Kotlin

Hardware acceleration for video ads

In order for video ads to show successfully in your banner 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.

Additional resources

Examples on GitHub

Banner ads example: Java | Kotlin

Advanced features demo: Java | Kotlin

Banner RecyclerView sample app: Java

Mobile Ads Garage video tutorials

Success stories

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.

Источник

Как внедрить баннеры в Android приложение не перекрыв другие элементы

Баннеры – один из наиболее популярных видов рекламы в мобильных приложениях. Они не занимают много места, как, например, полноэкранная (interstitial) реклама. И позволяют совместить их с элементами пользовательского интерфейса приложения. Их можно добавить на разные экраны в приложении.

Прочитав данную статью, вы узнаете, как лучше вставить баннеры таким образом, чтобы они не мешали пользователю и не портили вид приложения. При этом вам не придётся изменять layout xml и вносить много изменений в код приложения. Вы можете внедрить баннеры в своё готовое приложение, добавив всего несколько строк кода. Подход, описанный в статье, универсальный, вы можете использовать его для API любых рекламных сервисов. Статья будет интересна как для новичков, так и для опытных разработчиков. Если вы — новичок в разработке, то для того, чтобы понять предмет статьи, от вас не потребуется каких-либо глубоких знаний. Достаточно понимания базовых концепций разработки под Android. А опытные разработчики могут найти в ней готовое решение, которое они могут внедрить у себя. Но инициализация рекламного сервиса, работа с конкретными рекламными API и кеширование находятся за пределами данной статьи. Для решения таких вопросов, пожалуйста, обратитесь к руководству для вашего конкретного рекламного сервиса.

Идея статьи возникла от того, что в одном из наших приложений для Android нам было необходимо разместить баннеры в нескольких местах, но сделать это следовало таким образом, чтобы не испортить вид приложения и не перекрыть баннерами элементы управления. Код приложения был уже написан полностью и перекраивать его нам очень не хотелось, поэтому мы постарались сделать так, чтобы добавление баннеров было максимально простым, корректным и не затрагивало работу существующего кода. Другая причина — нам потребовалось создать платную версию приложения без рекламы. А если бы внедрение баннеров потребовало бы изменение layout xml, то это сильно бы усложнило создание версии без рекламы.

Чтобы было более наглядно и понятно то, о чём я пишу, посмотрите на следующий экран:

Элементы пользовательского интерфейса занимают всё пространство экрана. Пустых мест нет. В таком случае, мы можем разместить баннер внизу или вверху. Вариант размещения баннера снизу предпочтительнее, так как баннер будет находится подальше от кнопок и пользователь не заденет баннер, случайно пытаясь нажать на «Выбрать» или «Назад». Нам необходимо разместить баннер снизу экрана под GridView с фото. Так как баннер загружается по сети, он может быть не сразу и не всегда недоступен. Следовательно, не в каждый момент времени его можно показать и может получиться пустое место снизу. Если мы оставим это пустое место – получится очень некрасиво. Будет выглядеть, как будто это грубая недоработка дизайна интерфейса. Если мы разместим баннер поверх GridView, то он перекроет собой части фото и создаст неудобства пользователю, что тоже недопустимо.

Читайте также:  One across android app

Тогда сводим задачу к тому, что нам необходимо сделать так, чтобы не было дополнительных отступов. А когда баннер загружен и может быть показан – динамически добавить отступ снизу и показать баннер. С другой стороны, нам необходимо сделать код размещения баннеров максимально простым, без сложных инициализаций. Т.е. передавать id элементов или ссылки на контейнеры (ViewGroup) недопустимо. Вставлять баннеры в layout xml каждого экрана, куда нам необходимо добавить баннер – тоже недостустимо, т.к. потребует значительных изменений. В идеале, код установки баннера должен выглядеть следующим образом:

Всего одна строка кода, один вызов метода, которому передаётся только ссылка на Activity в которой будет размещён баннер. Такой код можно вставить в метод Activity onCreate.

Динамическое добавление отступа

Для того, чтобы это реализовать, нам необходимо знать, что находится в View и получить к этому доступ. Прямого метода для доступа к content view в Activity нет. Но благодаря пользователю nickes со StackOverflow мы нашли решение. Необходимо идти через Window, в котором находится Activity. У Window есть DecorView, а в DecorView находится ContentView. Первый дочерний элемент в нём – это и есть ViewGroup из layout xml.

Так что нам требуется Window, затем мы получаем DecorView, затем получаем ContentView и затем получаем первый дочерний элемент ContentView. И у этого дочернего элемента мы изменяем отступ:

Размещение баннера

Мы нашли решение, как динамически добавить отступ. Теперь нам необходимо разместить сам баннер. У разных рекламных сервисов разные API. У некоторых есть View баннера, который вы можете создать и добавить в ViewGroup. Но некоторые рекламные API не имеют доступа к View баннера, а имеют только метод, который показывает баннер. Рассмотрим оба варианта.

API, в котором есть View баннера

Назовём класс View баннера — Banner. (Чтобы узнать, как он реально называется в вашем случае и как с ним работать, пожалуйста, обратитесь к руководству вашего рекламного сервиса.)

Сначала, нам необходимо создать объект Banner:

Затем ему следует назначить слушатель событий. Нас интересует событие успешной загрузки баннера (это опять код — пример. Для того, чтобы узнать как слушатель называется и как его использовать, обратитесь, пожалуйста, к руководству вашего рекламного сервиса):

Когда баннер загружен, мы вызываем setupContentViewPadding, чтобы динамически добавить отступ снизу.

Затем мы добавляем наш баннер в Window. Мы добавляем его поверх существующих элементов. В классе Window есть метод addContentView для этого:

API без View баннера

У нас нет View баннера и мы не можем создать и разместить его явным образом. Но API имеет методы, вроде showBanner — показать баннер.

Я условно назову класс рекламного API — AdAPI (вам следует обратится к руководству вашего рекламного сервиса, чтобы узнать, как называется класс в которой есть методы размещения баннеров). В этом случае, код размещения баннера будет выглядеть примерно так:

Где BANNER_HEIGHT — константа равная высоте баннера.

Здесь возникают некоторые затруднения. Вам следует точно узнать или установить высоту баннера. У нас была такая проблема: мы запускали наше приложение на 3.7 дюймовом смартфоне и на 10.1 дюймовом планшете. Размеры баннера оказались разными на разных устройствах. На смартфоне баннер выглядел отлично, но на планшете он оказался слишком большим и отнял слишком много места у других элементов. Если ваш рекламный сервис позволяет явно задать высоту баннера — лучше задайте, чтобы не было таких неприятных неожиданностей.

Результат

Как вы можете видеть, баннер показан и не перекрывает другие элементы. Отступ снизу добавлен динамически.

Это то, что нам требовалось.

Использование

Подводя итог всему вышесказанному, привожу способ интеграции кода в ваше приложение.

Замените код в методе showBottomBanner на вызовы API вашего рекламного сервиса.

Чтобы разместить баннер, добавьте строчку кода Ads.showBottomBanner(this) в метод Activity onCreate.

Заключение

В статье я привёл описание как интегрировать баннеры в приложение наиболее корректным и простым способом. Есть и другие способы размещения баннеров. Например, можно взять первый экран показанный в статье и разместить баннер не снизу, а между элементами.

Надеюсь, статья была полезна для вас.

Пожалуйста, пишите ваши замечания в комментариях.

Благодарю за внимание. Успехов вам в разработке!

Источник

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