【Flutter】Android・iOSアプリ内にAdMob広告を表示する方法

Flutterアプリ内にAdMob広告を表示する方法についてまとめました。

スポンサーリンク

【手順1】firebase_admobプラグインを使う

Flutterでadmob広告を表示させる方法としては、Flutter公式の「firebase_admob」プラグインを使うのが定番です。
このプラグインでは、Firebase API を使ってAdMobのバナー広告、インタースティシャル広告、報酬付きのビデオ広告(リワード広告)をアプリ内に表示させることができます。

【参考】
firebase_core
firebase_admob

● pubspec.yaml に「firebase_core」「firebase_admob」プラグインを追加し、「flutter packages get」で更新します。

■pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  firebase_core:     # 追加
  firebase_admob: ^0.10.3  # 追加
  cupertino_icons: ^0.1.2
スポンサーリンク

【手順2】Androidアプリのみ

① Androidの場合、「AndroidManifest.xml」に以下の設定を追加します。

■/android/app/src/main/AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.app">

    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label="app"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- This keeps the window background of the activity showing
                 until Flutter renders its first frame. It can be removed if
                 there is no splash screen (such as the default splash screen
                 defined in @style/LaunchTheme). -->
            <meta-data
                android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
                android:value="true" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- ここからアプリIDを追加 -->
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-3940256099942544~3347511713"/>
        <!-- ここまでアプリIDを追加 -->
    </application>
</manifest>

※activity 以下にあるスプラッシュスクリーンの <meta-data> と並べると起動しないため注意

Firebase console から適当なプロジェクトを作成し、AndroidアプリをFirebaseに追加します。
(アプリの追加 -> Android で追加設定の画面を開き、AndroidバンドルID等は適宜設定)

● 構成ファイル(google-services.json)をダウンロードし、「プロジェクト名/android/app」内に保存します。

● 「プロジェクト名/android/build.gradle」を開き、以下の1行を追加します。

 dependencies {
  classpath 'com.android.tools.build:gradle:3.5.0'
  classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 
  classpath 'com.google.gms:google-services:4.3.3' # この行を追加
 }

● 「プロジェクト名/android/app/build.gradle」を開き、以下の1行を追加します。

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    implementation 'com.google.firebase:firebase-core:17.2.2' # この行を追加
}

● Android Studioの右上に表示される「Open for Editing in Android Studio」をクリックして「sync now」を実行し、build.gradleを更新します。

スポンサーリンク

【手順3】iOSアプリのみ

● iOSではInfo.plistにキーを追加します。

■ios/Runner/Info.Plist

<key>GADApplicationIdentifier</key>
<string>[AdMob AppID をここに入れる]</string>
<key>io.flutter.embedded_views_preview</key>
<true/>

Firebase console から適当なプロジェクトを作成し、iOSアプリをFirebaseに追加します。
(アプリの追加 -> iOS で追加設定の画面を開き、iOSバンドルID等は適宜設定)

● ②まで進んでGoogleService-Info.plistファイルをダウンロードします。
※③以降は何もせずにスキップします。

● iOS アプリプロジェクトのルートに追加します。
/ios以下に「GoogleService-Info.plist」ファイルを保存します。
(/ios/Runner.xcodeproj を XCode で開き、Runner/Runner以下にGoogleService-Info.plist を追加)

● ビルドして以下のエラーが出た場合、ios/Profileを削除しビルドし直します。

fatal error: module 'firebase_admob' not found @import firebase_admob;
スポンサーリンク

【手順4】バナー広告の設定

● バナー広告を表示させるコードを記述します。

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

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();

    // インスタンスを初期化(自分のアプリIDを挿入:今回はテスト用のアプリIDを利用)
    FirebaseAdMob.instance.initialize(appId: 'ca-app-pub-3940256099942544~3347511713');

    // バナー広告を表示する
    myBanner
      ..load()
      ..show(
        // ボトムからのオフセットで表示位置を決定
        anchorOffset: 0.0,
        anchorType: AnchorType.bottom,
      );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primarySwatch: Colors.blue),
      home: Scaffold(
        appBar: AppBar(title: Text('Firebase AdMob Demo')),
        body: Center(child: Text('バナー広告を表示')),
      ),
    );
  }
}

// 広告ターゲット
MobileAdTargetingInfo targetingInfo = MobileAdTargetingInfo(
  keywords: <String>['flutterio', 'beautiful apps'],
  contentUrl: 'https://flutter.io',
  birthday: DateTime.now(),
  childDirected: false,
  designedForFamilies: false,
  gender: MobileAdGender.male, // or female, unknown
  testDevices: <String>[], // Android emulators are considered test devices
);

BannerAd myBanner = BannerAd(
  // 広告ユニットID(テスト用のIDを使用、本番は自分の広告ユニットIDを利用)
  adUnitId: BannerAd.testAdUnitId,
  size: AdSize.smartBanner,
  targetingInfo: targetingInfo,
  listener: (MobileAdEvent event) {
    // 広告の読み込みが完了
    print("BannerAd event is $event");
  },
);

上記のコードでは、まずFirebaseAdMob のインスタンスを初期化し、そのあとに先ほど作成したバナー広告を追加しています。
そして、読み込み(load)を待ち、それを完了したら広告の表示(show)を行っています。
バナー広告はアンカーからのオフセットで表示位置を指定します(画面下部に固定するならオフセット0)。

● Flutterのビルドコマンドを実行します。

$ flutter build ios
スポンサーリンク

【エラー】Ad failed to load

次のようなエラー(Ad failed to load : 3)が発生した場合は、Admobの管理画面でGooglePlayと紐づけがされていないか、あるいは反映に時間がかかっているため広告が配信されない場合のエラーです。

E/FA      (10894): Uploading is not possible. App measurement disabled
I/p.co.orust.sal(10894): Waiting for a blocking GC ProfileSaver
W/Ads     (10894): Not retrying to fetch app settings
I/FA      (10894): Tag Manager is not found and thus will not be used
W/flutter (10894): onAdFailedToLoad: 3
I/Ads     (10894): Ad failed to load : 3
I/flutter (10894): BannerAd event is MobileAdEvent.failedToLoad

「Ad failed to load:2」なら、ネットワークセキュリティ上に問題がある場合です。

【Flutter入門】iOS、Android、Windowsアプリ開発
FlutterによるiOS、Android、Windowsアプリ開発について入門者向けに紹介します。
flutter
スポンサーリンク

コメント