인라인 적응형 배너

적응형 배너는 광고 크기를 기기별로 최적화하여 실적을 극대화하는 차세대 반응형 광고입니다. 고정된 높이만 지원하는 고정 크기 배너를 개선한 적응형 배너를 사용하면 개발자가 광고 너비를 지정하고 이를 통해 최적의 광고 크기를 결정할 수 있습니다.

최적의 광고 크기를 선택하기 위해 인라인 적응형 배너는 고정된 높이 대신 최댓값을 사용합니다. 이를 통해 실적을 개선할 수 있습니다.

인라인 적응형 배너를 사용해야 하는 경우

인라인 적응형 배너는 앵커 적응형 배너에 비해 더 크고 더 높은 배너입니다. 높이는 가변적이며 기기 화면 높이까지 가능합니다.

예를 들어 스크롤되는 콘텐츠에 배치되도록 고안되었습니다.

기본 요건

시작하기 전에

앱에서 적응형 배너를 구현하는 경우 다음 사항에 유의하세요.

  • 최신 버전의 Google 모바일 광고 SDK를 사용 중인지, 미디에이션을 사용하는 경우 최신 버전의 미디에이션 어댑터를 사용 중인지 확인하세요.

  • 인라인 적응형 배너 크기는 전체 너비를 사용할 때 가장 효과적으로 작동하도록 설계되었습니다. 대부분의 경우 사용 중인 기기 화면의 전체 너비입니다. 적용 가능한 안전 영역을 고려해야 합니다.

  • 적응형 크기가 적용되도록 새 광고 항목을 업데이트하거나 만들어야 할 수 있습니다. 자세히 알아보기

  • 광고 크기를 가져오는 메서드는 다음과 같습니다.

    • AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize(int width)
    • AdSize.getLandscapeInlineAdaptiveBannerAdSize(int width)
    • AdSize.getPortraitInlineAdaptiveBannerAdSize(int width)
    • AdSize.getInlineAdaptiveBannerAdSize(int width, int maxHeight)
  • 인라인 적응형 배너 API를 사용하면 Google 모바일 광고 SDK에서 지정된 너비와 인라인 플래그로 AdSize를 반환합니다. 높이는 사용 중인 API에 따라 0 또는 maxHeight입니다. 광고가 반환될 때 광고의 실제 높이를 확인할 수 있습니다.

  • 인라인 적응형 배너는 스크롤 가능한 콘텐츠에 삽입되도록 설계되었습니다. 배너의 높이는 API에 따라 기기 화면 높이 또는 최대 높이로 제한될 수 있습니다.

구현

간단한 인라인 적응형 배너를 구현하려면 아래 단계를 따르세요.

  1. 인라인 적응형 배너 광고 크기를 가져옵니다. 가져오는 크기는 적응형 배너를 요청하는 데 사용됩니다. 적응형 광고 크기를 가져오려면 다음을 확인하세요.
    1. 사용 중인 기기의 너비를 밀도 독립형 픽셀로 가져오거나 화면의 전체 너비를 사용하지 않으려는 경우 너비를 직접 설정합니다. MediaQuery.of(context)를 사용하여 화면 너비를 가져올 수 있습니다.
    2. AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize(int width)와 같은 광고 크기 클래스에 적절한 정적 메서드를 사용하여 현재 방향의 인라인 적응형 AdSize 객체를 가져옵니다.
    3. 배너의 높이를 제한하려면 정적 메서드 AdSize.getInlineAdaptiveBannerAdSize(int width, int maxHeight)를 사용하세요.
  2. 광고 단위 ID, 적응형 광고 크기, 광고 요청 객체를 사용하여 AdManagerBannerAd 객체를 만듭니다.
  3. 광고를 로드합니다.
  4. onAdLoaded 콜백에서 AdManagerBannerAd.getPlatformAdSize()를 사용하여 업데이트된 플랫폼 광고 크기를 가져오고 AdWidget 컨테이너 높이를 업데이트합니다.

코드 예시

다음은 인셋을 고려하여 화면 너비에 맞게 인라인 적응형 배너를 로드하는 위젯의 예입니다.

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();
  }
}