內嵌自動調整橫幅廣告

自動調整橫幅廣告是新一代的回應式廣告,可根據各種裝置的廣告大小進行最佳化,藉此提升成效。自動調整橫幅廣告僅支援固定高度,改善了固定大小的橫幅廣告,讓開發人員指定廣告的寬度,並據此決定最適合的廣告大小。

為了挑選最適合的廣告大小,內嵌自動調整橫幅廣告會採用最大高度,而非固定高度。進而提升成效。

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

與錨定自動調整橫幅廣告相比,內嵌自動調整橫幅廣告會尺寸更大、圖示也更高。它們的高度可變,高度與裝置螢幕高度一樣。

並用在捲動內容中,例如:

必要條件

事前準備

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

  • 確認您使用的是最新版的 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 而定,高度可以是 0 或 maxHeight。當系統傳回廣告時,即可使用廣告的實際高度。

  • 內嵌自動調整橫幅廣告適合放在可捲動內容中。橫幅廣告的高度可設為裝置螢幕的高度,或是設有高度上限,視 API 而定。

導入作業

請按照下列步驟導入簡單的內嵌自動調整橫幅廣告。

  1. 取得內嵌自動調整橫幅廣告大小。您取得的尺寸會用於請求自動調整橫幅廣告。如要取得自動調整廣告大小,請務必:
    1. 取得使用中的裝置寬度 (以密度獨立像素為單位),或者如果不想用整個螢幕的寬度,請自行設定寬度。您可以使用 MediaQuery.of(context) 取得螢幕寬度。
    2. 在廣告大小類別上使用適當的靜態方法,例如 AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize(int width),以取得目前螢幕方向的內嵌自動調整 AdSize 物件。
    3. 如要限制橫幅廣告的高度,可以使用靜態方法 AdSize.getInlineAdaptiveBannerAdSize(int width, int maxHeight)
  2. 使用您的廣告單元 ID、自動調整廣告大小和廣告請求物件,建立 BannerAd 物件。
  3. 載入廣告。
  4. onAdLoaded 回呼中,使用 BannerAd.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;
  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();
  }
}