Android mobile apps banner

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

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

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

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

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

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

Тогда сводим задачу к тому, что нам необходимо сделать так, чтобы не было дополнительных отступов. А когда баннер загружен и может быть показан – динамически добавить отступ снизу и показать баннер. С другой стороны, нам необходимо сделать код размещения баннеров максимально простым, без сложных инициализаций. Т.е. передавать 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.

Заключение

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

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

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

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

Источник

How to Set Up An iOS and Android Smart App Banner

Alex Austin

This blog post was originally published in 2015. It has been updated to reflect the current iOS landscape. You can also read one of our newer posts on how to use web to app banners on mobile.

It has been well known for a while that users prefer native mobile apps to mobile websites. However, deep linking to and from apps is not as robust as it should be compared to the web, so mobile websites are still a prominent part of mobile phone usage, especially for discovering new apps.

For example, imagine an existing user shares an article from your app to Facebook, and a number of new visitors click on that article. If you take them to the appropriate App Store page instead of showing them the article, there will be a lot of angry people who just close the store and go back to Facebook. This is where a mobile site with a Smart App Banner can come into play.

What Is A Smart App Banner?

A mobile smart banner uses a fraction of the screen on a mobile website to inform and encourage users to open the native app, or install it if they don’t have it. It’s a smart link that includes all the routing logic to automatically open up the app when it’s installed or fall back to an App Store page if not.

As you can see, the content is still available on this mobile site page without the app, but the banner at the top of the screen presents an option to download or open the app if the user so chooses. For new users, showing a mobile site with a banner delivers a clear and unobtrusive onboarding model, where they can interact with your mobile website and convert into full app users when ready.

Читайте также:  Copy file data android

What Does Apple’s iOS Smart App Banner Do?

In iOS 6, Apple released a fully integrated smart app banner into Safari. Its look and feel has evolved since then, into what you see below, but still functions the same way.

This banner has two different outcomes when clicked. If the app is installed, the banner will open it up by calling its URI scheme with accompanying deep link parameters. If the app is not installed, the banner will take the user to its App Store page.

Apple’s banner does have some unique characteristics that other 3rd party smart banners cannot easily replicate:

The call to action “View” will always change to “Open” when iOS detects that the app is installed.

While downloading the app, the smart banner will show a progress bar.

It also comes with some significant limitations:

It only works on iOS Safari.

The layout, color, and contents cannot be changed

No click or download tracking

Deep linking (taking users to specific content) only works if the app is already installed.

Is There An Android Smart App Banner?

Because of the fragmentation of the Android ecosystem and browser choice, Google has never released an Android smart banner. All Android developers have had to roll their own or adapt a pre-existing solution. This is a major hassle if you are a mobile developer who has built for both Android and iOS and desire consistent behavior and attribution measurement.

Apple’s introduction of the iOS smart banner spawned the development of a few different third-party options with Android compatibility. Unfortunately, progress on these alternatives has stalled in recent years, leaving developers out of luck once again. Here are a couple of the more popular examples:

The Branch Cross-Platform Smart App Banner

Tens of thousands of apps use Branch’s iOS or Android smart app banners on a daily basis to link to their app, using both dynamically generated links from the native iOS/Android SDKs and marketing links manually created on the Branch dashboard. These links work on every operating system and browser to deliver users to your app or to the App Store, depending on the situation.

Leveraging this expertise, we have built a fully customizable, cross-platform, trackable, deep linking smart app banner. Gone are the days of worrying about how to make a smart banner for your app’s mobile website, or about finding an external smart banner creator. By building a way to link from the web to app across all browsers, including Safari, Chrome, Firefox, and stock Android browsers, we’ve created a way to route your users to the platform with the highest engagement no matter which browser they use.

Example Branch banner on iOS:

Example Branch banner on desktop:

By using a Branch smart app banner, you get all the functionality of Apple’s iOS smart app banner plus these awesome features:

  1. Smart Routing to the Mobile App or Appropriate App Store

When the banner is tapped and the app is currently installed, it will open the app. If the app is not installed, it will take the user to the appropriate App Store page.

  1. Cross-Platform Support

Works on all mobile browsers and mobile operating systems. Easily create an iOS smart banner or Android smart banner once, and use everywhere.

  1. Installed App Detection

If you have the Branch SDK in your app and the user has opened at least once, we are able to automatically update the call to action from “Install” to “Open” just like Apple – or allow you to customize the respective call to action messages.

  1. Custom Audience Targeting

Tailor the Smart Banner look and feel as well as a call to action, based on specific behaviors of yours users both across mobile web and your app. For example, use a different banner for your most active users.

Without changing any code on your page, run experiments to identify the optimize Smart Banner audience targeting and creative to drive the greatest conversion of new app installs as well as app re-opens.

  1. Download Tracking
Читайте также:  Как очистить андроид zte

On the Branch dashboard, we provide rich analytics to track how many people viewed and clicked the banner, and how many installed or opened the app. This can tell you how well a mobile web page is converting, and help you optimize your growth efforts.

You can specify a dictionary of data that you want to pass into the app, so that you can take the user to a specific product, or piece of content within the app – also referred to as deep linking. Branch’s industry-leading matching accuracy means that you even receive those deep link parameters on first install from an App Store, in order to customize the onboarding flow for all users – newly acquired or re-engaged.

  1. Customizable Smart App Banner Creative – Layout, Color, Content, and Icons

To support a native look and feel with your mobile website, or just to customize the experience, Branch Journeys enables you to fully customize all visual aspects of your banner using a graphical editor or directly editing CSS. This includes the app title, description, call to action button, rating stars and number of reviews. It’s all tuneable to fit your site’s design.

Featuring Bnext and OneFootball

How to Configure the Universal Smart App Banner with Journeys

Branch also offers Journeys, a premium solution that allows you to codelessly create and deploy web to app assets such as smart banners. With Journeys, brands can:

1. Create an unlimited number of potential audiences based on web and app activity, referring site, operating system, and more.

2. Choose from a number of pre-built templates and have full control over the layout and design of your assets.

3. See real-time performance, segmented by Journey. Attribute down-funnel actions back to the Journey. Implement improvements without changing code.

Guide to Configure the Universal Smart App Banner

It’s very easy to get started with the Branch Journeys Smart App Banner. You can either follow the below step-by-step guide, or request a Branch demo to meet with a member of our team.

First, head to https://start.branch.io and follow the instructions. You’ll define all the different endpoints so that Branch knows where to redirect the user in every scenario.

Step 2: Add the Web SDK to Your Site

Next, retrieve your Branch key from the dashboard at https://dashboard.branch.io/#/settings . Paste the code snippet below into the Javascript tags on your site. Add the key you retrieved from the settings page in the ‘YOUR-BRANCH-KEY’ section.

Step 3: Set Up Your Journeys Smart App Banner

Step 4: Configure Your iOS or Android App for Deep Linking

Lastly, you can set up your native app for deferred deep linking and install tracking very easily by following the integration instructions located on this site for iOS or Android .

Deferred deep linking is a critical part of the web-to-app journey. When a user clicks a deep link that leads to an app but doesn’t have the app in question, a smart banner can offer them an easy way to get the app. Once they do download the app, Branch’s deep linking platform ensures that the user is taken to the initial link they had clicked, in the app. This process is called deferred deep linking.

As part of Apple’s release of iOS 15, the company has unveiled Private Relay , a feature that masks iCloud+ subscribers’ IP addresses, functioning like a VPN. This makes deferred deep linking more difficult on iOS, as IP addresses are often used to bridge the gap through the App Store.

Branch’s new NativeLink™ technology is a privacy-centric solution to this problem that eliminates the need for IP addresses and other personally identifiable data during the deferred deep linking process. Instead, NativeLink copies the user’s initial destination to their clipboard, and o nce app installation is complete, NativeLink pastes the URL, bringing the user directly to their original destination.

By using NativeLink, brands are able to provide a seamless deferred deep linking experience to all users — iCloud+ customers included — even with the launch of Private Relay.

Click here to learn how to start implementing NativeLink, and check out our video to learn how NativeLink works.

Источник

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