Banners adaptables intercalados

Los banners adaptables son la nueva generación de anuncios responsivos, ya que maximizan el rendimiento mediante la optimización del tamaño del anuncio en cada dispositivo. A fin de mejorar los banners de tamaño fijo, que solo admitían alturas fijas, los banners adaptables permiten a los desarrolladores especificar el ancho del anuncio y usarlo para determinar el tamaño de anuncio óptimo.

Para elegir el mejor tamaño de anuncio, los banners adaptables intercalados usan alturas máximas en lugar de fijas. Esto genera oportunidades para mejorar el rendimiento.

Cuándo usar banners adaptables intercalados

Los banners adaptables intercalados son banners más grandes y altos en comparación con los banners adaptables fijos. Tienen altura variable y pueden ser tan altas como la pantalla del dispositivo.

Están diseñados para colocarse en el contenido desplazable, por ejemplo:

Requisitos previos

Antes de comenzar

Cuando implementes banners adaptables en tu app, ten en cuenta los siguientes puntos:

  • Asegúrate de usar la versión más reciente del SDK de anuncios de Google para dispositivos móviles y, si usas la mediación, las versiones más recientes de tus adaptadores de mediación.

  • Los tamaños de banner adaptable intercalados están diseñados para funcionar mejor cuando se usa el ancho completo disponible. En la mayoría de los casos, será el ancho completo de la pantalla del dispositivo en uso. Asegúrate de tener en cuenta las áreas seguras aplicables.

  • Los métodos para obtener el tamaño del anuncio son los siguientes:

    • AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize(int width)
    • AdSize.getLandscapeInlineAdaptiveBannerAdSize(int width)
    • AdSize.getPortraitInlineAdaptiveBannerAdSize(int width)
    • AdSize.getInlineAdaptiveBannerAdSize(int width, int maxHeight)
  • Cuando se usan las APIs de banners adaptables intercalados, el SDK de anuncios de Google para dispositivos móviles muestra una AdSize con el ancho determinado y una marca intercalada. La altura es cero o maxHeight, según la API que uses. La altura real del anuncio está disponible cuando se muestra.

  • Un banner adaptable intercalado está diseñado para colocarse en contenido desplazable. El banner puede ser tan alto como la pantalla del dispositivo o estar limitado por una altura máxima, según la API.

Implementación

Sigue los pasos que se indican a continuación para implementar un banner adaptable simple y intercalado.

  1. Obtén un tamaño de anuncio de banner adaptable intercalado. El tamaño que obtengas se usará para solicitar el banner adaptable. Para obtener el tamaño del anuncio adaptable, asegúrese de hacer lo siguiente:
    1. Obtén el ancho del dispositivo en píxeles independientes de la densidad o establece el tuyo si no quieres usar el ancho completo de la pantalla. Puedes usar MediaQuery.of(context) para obtener el ancho de la pantalla.
    2. Usa los métodos estáticos adecuados en la clase de tamaño de anuncio, como AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize(int width), para obtener un objeto AdSize adaptable intercalado para la orientación actual.
    3. Si deseas limitar la altura del banner, puedes usar el método estático AdSize.getInlineAdaptiveBannerAdSize(int width, int maxHeight).
  2. Crea un objeto BannerAd con tu ID de unidad de anuncios, el tamaño de anuncio adaptable y un objeto de solicitud de anuncio.
  3. Carga el anuncio.
  4. En la devolución de llamada onAdLoaded, usa BannerAd.getPlatformAdSize() para obtener el tamaño actualizado del anuncio de plataforma y actualiza la altura del contenedor AdWidget.

Ejemplo de código

Este es un widget de ejemplo que carga un banner adaptable intercalado para adaptarse al ancho de la pantalla y tiene en cuenta las inserciones:

import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

/// This example demonstrates inline adaptive banner ads.
///
/// Loads and shows an inline adaptive banner ad in a scrolling view,
/// and reloads the ad when the orientation changes.
class InlineAdaptiveExample extends StatefulWidget {
  @override
  _InlineAdaptiveExampleState createState() => _InlineAdaptiveExampleState();
}

class _InlineAdaptiveExampleState extends State<InlineAdaptiveExample> {
  static const _insets = 16.0;
  BannerAd? _inlineAdaptiveAd;
  bool _isLoaded = false;
  AdSize? _adSize;
  late Orientation _currentOrientation;

  double get _adWidth => MediaQuery.of(context).size.width - (2 * _insets);

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _currentOrientation = MediaQuery.of(context).orientation;
    _loadAd();
  }

  void _loadAd() async {
    await _inlineAdaptiveAd?.dispose();
    setState(() {
      _inlineAdaptiveAd = null;
      _isLoaded = false;
    });

    // Get an inline adaptive size for the current orientation.
    AdSize size = AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize(
        _adWidth.truncate());

    _inlineAdaptiveAd = BannerAd(
      // TODO: replace this test ad unit with your own ad unit.
      adUnitId: 'ca-app-pub-3940256099942544/9214589741',
      size: size,
      request: AdRequest(),
      listener: BannerAdListener(
        onAdLoaded: (Ad ad) async {
          print('Inline adaptive banner loaded: ${ad.responseInfo}');

          // After the ad is loaded, get the platform ad size and use it to
          // update the height of the container. This is necessary because the
          // height can change after the ad is loaded.
          BannerAd bannerAd = (ad as BannerAd);
          final AdSize? size = await bannerAd.getPlatformAdSize();
          if (size == null) {
            print('Error: getPlatformAdSize() returned null for $bannerAd');
            return;
          }

          setState(() {
            _inlineAdaptiveAd = bannerAd;
            _isLoaded = true;
            _adSize = size;
          });
        },
        onAdFailedToLoad: (Ad ad, LoadAdError error) {
          print('Inline adaptive banner failedToLoad: $error');
          ad.dispose();
        },
      ),
    );
    await _inlineAdaptiveAd!.load();
  }

  /// Gets a widget containing the ad, if one is loaded.
  ///
  /// Returns an empty container if no ad is loaded, or the orientation
  /// has changed. Also loads a new ad if the orientation changes.
  Widget _getAdWidget() {
    return OrientationBuilder(
      builder: (context, orientation) {
        if (_currentOrientation == orientation &&
            _inlineAdaptiveAd != null &&
            _isLoaded &&
            _adSize != null) {
          return Align(
              child: Container(
            width: _adWidth,
            height: _adSize!.height.toDouble(),
            child: AdWidget(
              ad: _inlineAdaptiveAd!,
            ),
          ));
        }
        // Reload the ad if the orientation changes.
        if (_currentOrientation != orientation) {
          _currentOrientation = orientation;
          _loadAd();
        }
        return Container();
      },
    );
  }

  @override
  Widget build(BuildContext context) => Scaffold(
      appBar: AppBar(
        title: Text('Inline adaptive banner example'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: _insets),
          child: ListView.separated(
            itemCount: 20,
            separatorBuilder: (BuildContext context, int index) {
              return Container(
                height: 40,
              );
            },
            itemBuilder: (BuildContext context, int index) {
              if (index == 10) {
                return _getAdWidget();
              }
              return Text(
                'Placeholder text',
                style: TextStyle(fontSize: 24),
              );
            },
          ),
        ),
      ));

  @override
  void dispose() {
    super.dispose();
    _inlineAdaptiveAd?.dispose();
  }
}