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. Gracias a las mejoras en 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 óptimo del anuncio.

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 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 de desplazamiento, por ejemplo:

Requisitos previos

Antes de comenzar

Cuando implementes banners adaptables en tu app, ten en cuenta estos 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 banners adaptables 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 correspondientes.

  • Es posible que debas actualizar o crear líneas de pedido nuevas para trabajar con tamaños adaptables. Más información.

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

    • 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 un AdSize con el ancho especificado 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.

  • Los banners adaptables intercalados están diseñados 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 sencillo 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 de anuncio adaptable, asegúrese de hacer lo siguiente:
    1. Usa el ancho del dispositivo en píxeles independientes de la densidad o establece el tuyo propio 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 del 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 AdManagerBannerAd con tu ID de unidad de anuncios, el tamaño del anuncio adaptable y un objeto de solicitud de anuncio.
  3. Carga el anuncio.
  4. En la devolución de llamada onAdLoaded, usa AdManagerBannerAd.getPlatformAdSize() para obtener el tamaño actualizado del anuncio de la plataforma y 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;
  AdManagerBannerAd? _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 = AdManagerBannerAd(
      // TODO: replace with your own ad unit.
      adUnitId: '<your-ad-unit>',
      size: size,
      request: AdManagerAdRequest(),
      listener: AdManagerBannerAdListener(
        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.
          AdManagerBannerAd bannerAd = (ad as AdManagerBannerAd);
          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();
  }
}