- Key capabilities
- How does it work?
- Добавление AdMob рекламы в Android приложение с использованием Firebase
- Предисловие
- Давайте посмотрим как с этим жить теперь
- Add mobile to android
- Get Started
- Before you begin
- App prerequisites
- Set up your app in your AdMob account
- Configure your app
- Initialize the Google Mobile Ads SDK
- Example MainActivity (excerpt)
- Kotlin
- Select an ad format
- Banner
- Interstitial
- Native
- Rewarded
- Additional resources
Google AdMob is a mobile advertising platform that you can use to generate revenue from your app.
Key capabilities
Earn more from AdMob’s in-app ads | |
Improve user experience | Native and video ads create a positive user experience as you monetize by matching the look and feel of your app. Choose from different ad templates, customize them, and experiment with different layouts on the fly without republishing your app. |
Scale fast | |
Access monetization reports | AdMob is the premier monetization platform for mobile. While generating ad revenue, AdMob also produces its own monetization reports that you can use to make smarter decisions about product strategy. |
How does it work?
AdMob helps you monetize your mobile app through in-app advertising. Ads can be displayed in a number of formats and are seamlessly added to platform native UI components.
Before you can display ads within your app, you’ll need to create an AdMob account and activate one or more ad unit IDs. This is a unique identifier for the places in your app where ads are displayed.
AdMob uses the Google Mobile Ads SDK which helps app developers gain insights about their users and maximize ad revenue. To do so, the default integration of the Mobile Ads SDK collects information such as device information.
Источник
Добавление AdMob рекламы в Android приложение с использованием Firebase
Предисловие
Вводим «AdMob» в Google и первым сайтом уже будет не AdMob-ский, а Google-ский сайт. После перехода на оный Вас начнут по немногу переманивать на темную сторону Firebase (недавно купленный Google).
Firebase дает довольно обширные возможности по аналитике (по крайней мере для меня, как программиста, а не маркетолога) рекламы в вашем приложениее (рост, вес, страна, кол-во просмотров, версии Android куда установливалось и тд. и тп.).
Первым делом был найден пост, но он для Eclipse, а после первых попыток сделать по примеру — начались предупреждения о depricated да и вообще ошибки.
Прочитав больше информации стало понятно, что переход AdMob на firebase произошел недавно и разбиратся придется самому.
Давайте посмотрим как с этим жить теперь
Минимальные требования: (с учетом которых была написана статья).
- Android Studio 2.2.2
- Быть зарегистрированным в Google Developer Console
- Быть зарегистрированным на AdMob
Мозг
Шаг 1
Добавляем зависимости в build.gradle файлы. Первым делом в ‘Module: app’:
Теперь во второй (‘Project: AdMobOnHabr’):
После чего рекомендуется сделать Tools → Android → «Sync Project with Gradle Files» и скомпилировать проект. Видимого результата еще нету, но главное — ошибок нету? Отлично! Идем дальше.
Шаг 2
Входим в свой аккаунт на AdMob. Выбираем ручное добавление приложения (если Ваше приложение уже опубликовано в Google Play — воспользуйтесь поиском в первой вкладке).
Добавим в наше приложение рекламный баннер (с другими видами предлагаю ознакомится самостоятельно). Частоту обновления Я выбрал минимально допустимую — 30 сек., название рекламного блока на Ваше усмотрение.
Дальше Вам предложат «Настройте Firebase Analytics (необязательно)» — нужное слово подчеркул. Пока что это ни к чему — пропускаем. Ознакамливаемся с «инструкциями по интеграции», жмем Готово. После переадресации видим страницу и долгожданный ID рекламного блока:
Добавляем ad unit ID в strings.xml:
Не забудьте, что для рекламного блока на другой Activity нужен новый ID.
Шаг 3
Добавляем AdView элемент на activity_admobbanner.xml:
В атрибут ‘ads:adUnitId’ записываем ресурс из strings.xml с ID рекламного блока.
Несколько советов и заметок:
- Не перепутайте ads и app при добавлении namespace в родительский ViewGroup;
На API Совет по Code Style тэга
Google рекомендует писать тэг закрывая так:
Шаг 4
Инициализируем Google Mobile Ads SDK. Для этого Вам понадобится app ID взятый с AdMob. Жмем шестеренку справа вверху → Управление приложением:
Вот оно, счастье нужный app ID:
Пишем саму, собственно, инициализацию используя свой app ID:
Шаг 5
Последнее действие по версии Google — загрузить долгожданную рекламу в AdView элемент:
На эмуляторе следуя политике AdMob вы не можете выводить реальную рекламу (показывается только тестовая). Довольно логично. Но если у Вас есть реальное устройство — можете протестировать рекламу в действии на нем и порадовать себя успехом.
- Для отображения рекламы на реальном тестовом девайсе перепишите код вот так:
Остается вопрос — где взять волшебный DEVICE_ID_EMULATOR? Все в один голос рекомендуют очень «трушный» способ: пишите вместо DEVICE_ID_EMULATOR любое значение, к примеру:
После чего запускаете приложение на своем устройстве и смотрите logcat. Там найдете лог подобный этому:
Что делать дальше ясно — копируйте полученный код в метод упомянутый выше и радуйтесь жизни.
Заметка:
Дело было ночью, спать хотелось, в общем не повторяйте моих ошибок:
При поиске ID вашего реального устройства — не забудьте выбрать logcat девайса, на котором запущено приложение (у меня, к примеру, было запущено еще несколько эмуляторов и Я упорно не мог понять почему в лог эмулятора не выводится так нужный мне ID)
Вроде бы все сделали как написано, все должно работать, а нам пора ложится спать работать над следующей фичей но…
Шаг 6
Где-то между строк Вы должны были прочитать, что без google-services.json оно работать не будет. Скорее всего, даного файла у Вас еще нету. Давайте искать вместе.
Google любезно предоставляет Вам «простыни» инструкций как сделать google-services.json. Но у меня возник вопрос — неужели в 2к16 году нужно самому сидеть и писать этот файл, который, к всему, скорее всего довольно шаблонный?
Ответ находится в Google Developer Console, где все таки подумали про желание ленивого программиста.
Жмем Continue. Выбираем Google Sing-In. Дальше просто — Вы же знаете на память свой SHA-1?
Если вдруг запамятовали — могу помочь. SHA-1 можно узнать с помощью keyltool или немного по-топорному — через gradle в самой AS . Так как лишних действий делать не хочется — выберем второй способ:
Вставляем полученый SHA-1 код, жмем «Enable Google Sign-In» и «Continue to Generate configuration files».
Ну, вы поняли. Скачиваем сгенерированный файл и копируем в корневой каталог приложения:
Собираем свой проект — готово. Путем подобных несложных манипуляций в Вашем приложении теперь есть реклама.
Источник
Add mobile to android
Google Mobile Ads SDK for Android
The Google Mobile Ads SDK is the latest generation in Google mobile advertising, featuring refined ad formats and streamlined APIs for access to mobile ad networks and advertising solutions. The SDK enables mobile app developers to maximize their monetization in native mobile apps.
This repository contains open source examples and developer resources for both the Google AdMob and Google Ad Manager components of the Google Mobile Ads SDK.
Google Mobile Ads SDK Developers forum
To report SDK feature requests, bugs, and crashes or to browse SDK-related discussions, please use our Google Mobile Ads SDK Developers forum. The forum provides the latest SDK announcements and updates as well as technical SDK support for our Android developers.
Check out our developers site for documentation on using the Mobile Ads SDK.
- App Open: Java, Kotlin
- Banner: Java, Kotlin
- Interstitial: Java, Kotlin
- Rewarded Interstitial: Java, Kotlin
- Rewarded Video: Java, Kotlin
- Native Advanced: Java, Kotlin
- API Demo: Java, Kotlin — Provides additional examples for both AdMob and Ad Manager to help improve your mobile app integration of the Google Mobile Ads SDK.
- Banner RecyclerView: Java — Provides an example for displaying ads from AdMob Banner ads in a RecyclerView widget.
- App Open: Java, Kotlin
- Banner: Java, Kotlin
- Interstitial: Java, Kotlin
- Rewarded Interstitial: Java, Kotlin
- Rewarded Video: Java, Kotlin
- Native Ads: Java, Kotlin
Please check out our releases for the latest downloads of our example apps.
GitHub issue tracker
To file bugs, make feature requests, or suggest improvements for the Android example apps, please use GitHub’s issue tracker.
For SDK support issues, please use the Google Mobile Ads SDK Developers forum.
Источник
Get Started
Integrating the Google Mobile Ads SDK into an app is the first step toward displaying ads and earning revenue. Once you’ve integrated the SDK, you can choose an ad format (such as native or rewarded video) and follow the steps to implement it.
Before you begin
To prepare your app, complete the steps in the following sections.
App prerequisites
- Use Android Studio 3.2 or higher
Make sure that your app’s build file uses the following values:
- A minSdkVersion of 16 or higher
- A compileSdkVersion of 28 or higher
Set up your app in your AdMob account
Register your app as an AdMob app by completing the following steps:
Register your app with AdMob. This step creates an AdMob app with a unique AdMob App ID that is needed later in this guide.
Configure your app
In your project-level build.gradle file, include Google’s Maven repository and Maven central repository in both your buildscript and allprojects sections:
Add the dependencies for the Google Mobile Ads SDK to your module’s app-level Gradle file, normally app/build.gradle :
Add your AdMob app ID (identified in the AdMob UI) to your app’s AndroidManifest.xml file. To do so, add a tag with android:name=»com.google.android.gms.ads.APPLICATION_ID» . You can find your app ID in the AdMob UI. For android:value , insert your own AdMob app ID, surrounded by quotation marks.
In a real app, use your actual AdMob app ID, not the one listed above. If you’re just looking to experiment with the SDK in a Hello World app, you can use the sample app ID shown above.
Note also that failure to add the tag as shown above results in a crash with the message:
(Optional) Declare AD_ID permission for previous versions to work with Android S.
If your app uses the Google Mobile Ads SDK version 20.4.0 or higher, you can skip this step since the SDK automatically declares the com.google.android.gms.permission.AD_ID permission and is able to access the Advertising ID whenever it’s available.
For apps that use the Google Mobile Ads SDK version 20.3.0 or lower and are targeting Android S, you must add the com.google.android.gms.permission.AD_ID permission in the AndroidManifest.xml file in order to target Android S:
To learn more about the com.google.android.gms.permission.AD_ID permission declaration, including how to disable it, please refer to this Play Console article.
Initialize the Google Mobile Ads SDK
Before loading ads, have your app initialize the Google Mobile Ads SDK by calling MobileAds.initialize() which initializes the SDK and calls back a completion listener once initialization is complete (or after a 30-second timeout). This needs to be done only once, ideally at app launch.
Ads may be preloaded by the Google Mobile Ads SDK or mediation partner SDKs upon calling MobileAds.initialize() . If you need to obtain consent from users in the European Economic Area (EEA), set any request-specific flags (such as tagForChildDirectedTreatment or tag_for_under_age_of_consent ), or otherwise take action before loading ads, ensure you do so before initializing the Google Mobile Ads SDK.
Here’s an example of how to call the initialize() method in an Activity:
Example MainActivity (excerpt)
Kotlin
If you’re using mediation, wait until the completion handler is called before loading ads, as this will ensure that all mediation adapters are initialized.
Select an ad format
The Google Mobile Ads SDK is now imported and you’re ready to implement an ad. AdMob offers a number of different ad formats, so you can choose the one that best fits your app’s user experience.
Banner
Rectangular ads that appear at the top or bottom of the device screen. Banner ads 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.
Interstitial
Full-screen ads that cover the interface of an app until closed by the user. They’re best used at natural pauses in the flow of an app’s execution, such as between levels of a game or just after a task is completed.
Native
Customizable ads that match the look and feel of your app. You decide how and where they’re placed, so the layout is more consistent with your app’s design.
Rewarded
Ads that reward users for watching short videos and interacting with playable ads and surveys. Used for monetizing free-to-play apps.
Additional resources
The Google Mobile Ads repository on GitHub demonstrates how to use the different ad formats that this API offers.
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.
Источник