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.
This guide gets you started with anchored adaptive banner ads . Anchored adaptive banners optimizes the ad size for each device using an ad width you specify.
Адаптивные баннерные объявления с привязкой к определенной ширине — это объявления с фиксированным соотношением сторон, а не фиксированным размером . Соотношение сторон аналогично 320x50. После указания доступной полной ширины Google Mobile Ads Flutter Plugin возвращает объявление с оптимальной высотой для этой ширины. Оптимальная высота объявления остается постоянной при разных запросах, а контент вокруг объявления остается на месте после обновления страницы.
Всегда проводите тестирование с помощью тестовых объявлений.
При разработке и тестировании приложений обязательно используйте тестовые объявления, а не реальные, рабочие объявления. Несоблюдение этого правила может привести к блокировке вашего аккаунта.
Самый простой способ загрузить тестовые объявления — использовать наш специальный идентификатор тестового рекламного блока для баннеров:
Android
ca-app-pub-3940256099942544/9214589741
iOS
ca-app-pub-3940256099942544/2435281174
Тестовые рекламные блоки настроены на возврат тестовых объявлений при каждом запросе, и вы можете свободно использовать их в своих приложениях во время кодирования, тестирования и отладки. Просто убедитесь, что вы заменили их на свои собственные идентификаторы рекламных блоков перед публикацией приложения.
Узнать размер рекламы
Чтобы запросить баннерную рекламу нужного размера, выполните следующие действия:
Получите ширину экрана устройства в пикселях, не зависящих от плотности (dp), используя
MediaQuery.of(context). Если вы не хотите использовать всю ширину экрана, вы можете задать свою собственную ширину.Use the appropriate static method on the
AdSizeclass to get anAdSizeobject. For example, useAdSize.getLargeAnchoredAdaptiveBannerAdSize(int width)to get the ad size for the current orientation.
// Get an AnchoredAdaptiveBannerAdSize before loading the ad.
final size = await AdSize.getLargeAnchoredAdaptiveBannerAdSize(
MediaQuery.sizeOf(context).width.truncate(),
);
Загрузить рекламу
В следующем примере загружается баннерная реклама:
Замените _adUnitId на идентификатор вашего рекламного блока.
события баннерной рекламы
С помощью BannerAdListener вы можете отслеживать события жизненного цикла, например, загрузку объявления. В этом примере реализованы все методы и выведено сообщение в консоль:
onAdOpened: (Ad ad) {
// Called when an ad opens an overlay that covers the screen.
debugPrint("Ad was opened.");
},
onAdClosed: (Ad ad) {
// Called when an ad removes an overlay that covers the screen.
debugPrint("Ad was closed.");
},
onAdImpression: (Ad ad) {
// Called when an impression occurs on the ad.
debugPrint("Ad recorded an impression.");
},
onAdClicked: (Ad ad) {
// Called when an a click event occurs on the ad.
debugPrint("Ad was clicked.");
},
onAdWillDismissScreen: (Ad ad) {
// iOS only. Called before dismissing a full screen view.
debugPrint("Ad will be dismissed.");
},
Обновить рекламу
If you configured your ad unit to refresh, you don't need to request another ad when the ad fails to load. Google Mobile Ads Flutter Plugin respects any refresh rate you specified in the AdMob UI. If you haven't enabled refresh, issue a new request. For more details on ad unit refresh, such as setting a refresh rate, see Use automatic refresh for Banner ads .
Показать баннерную рекламу
To display a BannerAd as a widget, you must instantiate an AdWidget with a supported ad after calling load() . You can create the widget before calling load() , but load() must be called before adding it to the widget tree.
AdWidget inherits from Flutter's Widget class and can be used like any other widget. On iOS, make sure you place the widget in a widget with a specified width and height. Otherwise, your ad may not be displayed. A BannerAd can be placed in a container with a size that matches the ad:
if (_bannerAd != null)
Align(
alignment: Alignment.bottomCenter,
child: SafeArea(
child: SizedBox(
width: _bannerAd!.size.width.toDouble(),
height: _bannerAd!.size.height.toDouble(),
child: AdWidget(ad: _bannerAd!),
),
),
),
An ad must be disposed when access to it is no longer needed. The best practice for when to call dispose() is either after the AdWidget is removed from the widget tree or in the BannerAdListener.onAdFailedToLoad() callback.
Вот и всё! Ваше приложение готово к показу баннерной рекламы.
Ограничение на прокрутку в Android 9 и более ранних версиях.
We are aware that some older or less powerful devices running Android 9 or earlier may have suboptimal performance when displaying inline banner ads within scrolling views. We recommend only using these types of banners on Android 10 or later. Fixed position banners such as anchored banners are not affected and can be used with optimal performance on all Android API levels.
Полный пример на GitHub
Полный пример интеграции баннера, описанный на этой странице, можно посмотреть в файле banner_example .
Узнайте о других типах баннеров
Ознакомьтесь с другими типами баннеров, описанными в этом разделе, для вашего Flutter-приложения.
Встроенные адаптивные баннеры
Inline adaptive banners have variable height and are larger, taller banners compared to anchored adaptive banners. Inline adaptive banners are recommended over anchored adaptive banner ads for apps that place banner ads in scrollable content. For more details, see inline adaptive banners .
Складные баннеры
Collapsible banner ads are banner ads that are initially presented as a larger overlay, with a button to collapse the ad to a smaller size. Consider using this banner to further optimize your performance. For more details, see collapsible banner ads .