內嵌自動調整橫幅廣告

選取平台: Android iOS Flutter

自動調整橫幅廣告是新一代的回應式廣告,能配合裝置調整大小來提升成效。相較於僅支援固定高度的固定大小橫幅廣告,自動調整橫幅廣告可讓開發人員指定廣告寬度,並根據這個寬度計算出最佳廣告大小。

為了顯示最理想的廣告大小,內嵌自動調整橫幅廣告會使用可用的最大高度來取代固定高度,進而提升成效。

內嵌自動調整橫幅廣告的使用時機

與錨定自動調整橫幅廣告相比,內嵌自動調整橫幅廣告的版面更大、更高,而且高度不固定,最高等同裝置螢幕高度。

這類廣告適合置於捲動瀏覽的內容中,例如:

前置作業

事前準備

在應用程式中導入自動調整橫幅廣告時,請注意以下事項:

  • 確認使用最新版 Google Mobile Ads SDK;若使用中介服務,轉接程式也應為最新版本。

  • 內嵌自動調整橫幅廣告在採用最大可用寬度時效果最佳,這通常是指裝置螢幕的全寬。請務必考慮到需保留的安全區域。

  • 您可能需要更新或建立新的委刊項,才能支援自動調整大小。瞭解詳情

  • 以下是取得廣告大小的方法

    • AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize(int width)
    • AdSize.getLandscapeInlineAdaptiveBannerAdSize(int width)
    • AdSize.getPortraitInlineAdaptiveBannerAdSize(int width)
    • AdSize.getInlineAdaptiveBannerAdSize(int width, int maxHeight)
  • 使用內嵌自動調整橫幅廣告 API 時,Google Mobile Ads SDK 會傳回包含指定寬度和內嵌標記的 AdSize。高度依使用的 API 而定,可能是零或 maxHeight。實際高度在廣告載入後才會確定。

  • 內嵌自動調整橫幅廣告適合放在可捲動的內容中。高度依所用 API 而定,可能與裝置螢幕等高,或受到最大高度限制。

導入方式

您可以依照下列步驟,導入簡單的內嵌自動調整橫幅廣告:

  1. 取得內嵌自動調整橫幅廣告的尺寸。這個尺寸會用於請求自動調整橫幅廣告。請確實完成下列步驟:
    1. 取得目前裝置的寬度 (以密度獨立像素計算);如果不想使用螢幕全寬,也可以自行設定寬度。您可以使用 MediaQuery.of(context) 取得螢幕寬度。
    2. 針對廣告尺寸類別使用適當的靜態方法 (例如 AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize(int width)),取得符合目前螢幕方向的內嵌自動調整 AdSize 物件。
    3. 如要限制橫幅高度,可以使用靜態方法 AdSize.getInlineAdaptiveBannerAdSize(int width, int maxHeight)
  2. 建立 AdManagerBannerAd 物件,並指定廣告單元 ID、自動調整廣告大小和廣告請求物件。
  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: '/21775744923/example/adaptive-banner',
      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();
  }
}