如何在 flutter 应用中集成 google 移动广告

How to integrate google mobile ads in flutter app

最近 flutter 宣布发布 Google Mobile Ads for Flutter,这是一种新的 SDK,可与 AdMob 和 AdManager 配合使用,提供多种广告格式,包括横幅广告、插页式广告、原生广告和用于 flutter 的奖励视频广告

我想通过 AdMob 展示广告来通过我的 Flutter 应用获利。我们如何在我们的 Flutter 应用程序中设置和集成 google 移动广告

Google Flutter 移动广告 SDK 目前支持加载和显示横幅广告、插播广告(全屏)、原生广告和奖励视频广告

将 Google 移动广告 SDK 集成到 Flutter 应用中,您将在此处执行此操作

先决条件:https://pub.dev/packages/google_mobile_ads#prerequisites

添加 Google 移动广告插件作为依赖项

Google Mobile Ads 插件作为依赖项添加到位于项目根目录的 pubspec.yaml 文件。

dependencies:
  google_mobile_ads: ^0.11.0+1

在你的Dart代码中导入,你可以使用:

import 'package:google_mobile_ads/google_mobile_ads.dart';

针对特定平台的设置

iOS

更新您的 Info.plist

  1. 在 Android Studio 中打开 ios/Runner/Info.plist 文件。

  2. 使用您的 AdMob 应用 ID (identified in the AdMob UI) 的字符串值添加一个 GADApplicationIdentifier 键,如下所示:

<key>GADApplicationIdentifier</key>
<string>ca-app-pub-################~##########</string>

Android

更新AndroidManifest.xml

  1. 在 Android Studio 中打开 android/app/src/main/AndroidManifest.xml 文件。

  2. 通过添加 <meta-data> 标签并输入 com.google.android.gms.ads.APPLICATION_ID 添加您的 AdMob 应用 ID。如下所示。您可以在 AdMob UI 中找到您的 App ID。对于 android:value,请在引号中插入您自己的 AdMob 应用 ID,如下所示。

     <!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
     <meta-data
          android:name="com.google.android.gms.ads.APPLICATION_ID"
          android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
    

AdMob 应用 ID 必须包含在 AndroidManifest.xml 中。否则将导致应用启动时崩溃。

初始化移动广告 SDK

在加载广告之前,让您的应用初始化移动广告 SDK,方法是调用 MobileAds.instance.initialize() 初始化 SDK,然后 returns 一个 Future 在初始化完成后(或在30 秒超时)。这只需要完成一次,最好是在 运行 应用程序之前。

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  MobileAds.instance.initialize();

  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    // Load ads.
  }
}

这是一个添加横幅广告供所有人查看googleads-mobile-flutter

BannerAd 需要一个 adUnitId、一个 AdSize、一个 AdRequest 和一个 AdListener。下面显示了一个示例以及有关每个参数的更多信息。

final BannerAd myBanner = BannerAd(
  adUnitId: '<ad unit id>',
  size: AdSize.banner,
  request: AdRequest(),
  listener: AdListener(),
);

要定义自定义横幅尺寸,请设置所需的广告尺寸,如下所示:

final AdSize adSize = AdSize(300, 50);

横幅广告事件

通过使用 AdListener,您可以监听生命周期事件,例如广告关闭或用户离开应用程序的时间。此示例实现每个方法并将消息记录到控制台:

final AdListener listener = AdListener(
 // Called when an ad is successfully received.
 onAdLoaded: (Ad ad) => print('Ad loaded.'),
 // Called when an ad request failed.
 onAdFailedToLoad: (Ad ad, LoadAdError error) {
   print('Ad failed to load: $error');
 },
 // Called when an ad opens an overlay that covers the screen.
 onAdOpened: (Ad ad) => print('Ad opened.'),
 // Called when an ad removes an overlay that covers the screen.
 onAdClosed: (Ad ad) => print('Ad closed.'),
 // Called when an ad is in the process of leaving the application.
 onApplicationExit: (Ad ad) => print('Left application.'),
);

BannerAd实例化后,必须调用load()才能显示在屏幕上。

myBanner.load();

要显示 BannerAd 作为小部件,您必须在调用 load() 后用受支持的广告实例化 AdWidget。您可以在调用 load() 之前创建小部件,但必须在将其添加到小部件树之前调用 load()

final AdWidget adWidget = AdWidget(ad: myBanner);

AdWidget 继承自 Flutter 的 Widget class,可用作任何其他小部件。在 iOS 上,确保将小部件放置在具有指定宽度和高度的小部件中。否则,您的广告可能无法展示。 BannerAd 可以放置在尺寸与广告匹配的容器中:

final Container adContainer = Container(
  alignment: Alignment.center,
  child: adWidget,
  width: myBanner.size.width.toDouble(),
  height: myBanner.size.height.toDouble(),
);

最后,通过在dispose()回调方法中调用BannerAd.dispose()方法释放与BannerAd对象关联的资源。

@override
void dispose() {
  // TODO: Dispose BannerAd object
  myBanner?.dispose();
  super.dispose();
}

就是这样!您的应用现在可以显示横幅广告了。

完整示例

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


void main() {
  runApp(MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyApp()));
}

// You can also test with your own ad unit IDs by registering your device as a
// test device. Check the logs for your device's ID value.
const String testDevice = 'YOUR_DEVICE_ID';

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

class _MyAppState extends State<MyApp> {

  BannerAd _bannerAd;

  @override
  void initState() {
    super.initState();
    _bannerAd = BannerAd(
      adUnitId: BannerAd.testAdUnitId,
      request: AdRequest(),
      size: AdSize.banner,
      listener: AdListener(
        onAdLoaded: (Ad ad) {
          print('$BannerAd loaded.');
        },
        onAdFailedToLoad: (Ad ad, LoadAdError error) {
          print('$BannerAd failedToLoad: $error');
        },
        onAdOpened: (Ad ad) => print('$BannerAd onAdOpened.'),
        onAdClosed: (Ad ad) => print('$BannerAd onAdClosed.'),
        onApplicationExit: (Ad ad) => print('$BannerAd onApplicationExit.'),
      ),
    );

    _bannerAd?.load();
  }

  @override
  void dispose() {
    super.dispose();
    _bannerAd?.dispose();
    _bannerAd = null;
  }

  @override
  Widget build(BuildContext context) {
    final AdWidget adWidget = AdWidget(ad: _bannerAd);
    return Scaffold(
      appBar: AppBar(
        title: const Text('Google Mobile Ads'),
        actions: <Widget>[
        ],
      ),
      body: Column(
        children: [
          Align(
            alignment: FractionalOffset.topCenter,
            child: Padding(
                padding: EdgeInsets.only(top: 10.0),
                child: Container(
                  alignment: Alignment.center,
                  child: adWidget,
                  width: _bannerAd.size.width.toDouble(),
                  height: _bannerAd.size.height.toDouble(),
                )
            ),
          )
        ],
      ),
    );
  }
}

幸好有 Ads support for Flutter 的现有文档。

Monetizing apps by using ads has been one of the most popular requests for many Flutter developers.

Flutter ads support is available through the Google Mobile Ads SDK for Flutter (Beta), which works with both AdMob and AdManager. This plugin supports a variety of ad formats, including banner (inline and overlay), interstitial, rewarded video, native ads, and adaptive banner.

The following video tutorial, Monetizing apps with Flutter, shows how to get started with Ads:

The following resources can help you get started:

第 1 步:将依赖项添加到 pubspec.yaml

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2

  google_mobile_ads: ^0.13.0 #this

第 2 步:在 IOS 中更新您的 Info.plist 并在 Android

中更新 AndroidManifest.xml

对于IOS

<key>GADApplicationIdentifier</key>
<string>ca-app-pub-3940256099942544~1458002511</string>
<key>SKAdNetworkItems</key>
  <array>
    <dict>
      <key>SKAdNetworkIdentifier</key>
      <string>cstr6suwn9.skadnetwork</string>
    </dict>
  </array>

对于Android

<manifest>
    <application>
        <!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
    </application>
</manifest>

第 2 步:在 main.dart

中初始化移动广告 SDK
import 'package:flutter/material.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await MobileAds.instance.initialize().then((InitializationStatus status) {
    print('Initialization done: ${status.adapterStatuses}');
    MobileAds.instance.updateRequestConfiguration(
      RequestConfiguration(
          tagForChildDirectedTreatment:
              TagForChildDirectedTreatment.unspecified,
          testDeviceIds: <String>[]),//when you run first time you will get your test id in logs then update it here <String>["test id"]
    );
  });
  runApp(MyApp());
}

Admob 中的步骤 4:Create 广告单元 然后我们准备实施广告

步骤 5:Make 确保在 app/build.gradle 文件

中启用 multidex
defaultConfig {
        ....
        minSdkVersion 19
        multiDexEnabled true
    }

dependencies {
    ....
    implementation 'com.android.support:multidex:2.0.1'
}

第 6 步:创建 admanager.dart 文件

import 'package:google_mobile_ads/google_mobile_ads.dart';

AdRequest request = AdRequest(
  keywords: <String>[
    'foo',
    'bar',
    'wallpaper',
  ],
  contentUrl: 'URL',
  nonPersonalizedAds: true,
);

final BannerAd myBanner = BannerAd(
  adUnitId: 'ca-app-pub-3166882328175414/3480332744',
  size: AdSize.banner,
  request: request,
  listener: BannerAdListener(
        onAdLoaded: (Ad ad) {
          print('$BannerAd loaded.');
        },
        onAdFailedToLoad: (Ad ad, LoadAdError error) {
          print('$BannerAd failedToLoad: $error');
          ad.dispose();
        },
        onAdOpened: (Ad ad) => print('$BannerAd onAdOpened.'),
        onAdClosed: (Ad ad) => print('$BannerAd onAdClosed.'),
      ),
);


final AdWidget adWidget = AdWidget(ad: myBanner);

第 7 步:现在转到主页使用它

import 'package:flutter/material.dart';
import 'package:vaccine/adManger.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  void initState() {
    myBanner.load();
    super.initState();
  }

  final Container adContainer = Container(
    alignment: Alignment.center,
    child: adWidget,
    width: myBanner.size.width.toDouble(),
    height: myBanner.size.height.toDouble(),
  );

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [                        
                      adContainer,
                    ],
                  ),
               ),
            );
  }
}

谢谢

flutter 2.8 添加 Google Admobs

添加依赖项

google_mobile_ads: ^1.0.1

导入

进口'package:google_mobile_ads/google_mobile_ads.dart';

转到 android/local.properties 并添加版本

  • flutter.minSdkVersion=21
  • flutter.targetSdkVersion=30
  • flutter.compileSdkVersion=30

转到 android/app/build.gradle 并添加

-minSdkVersion localProperties.getProperty('flutter.minSdkVersion').toInteger()

-targetSdkVersion localProperties.getProperty('flutter.targetSdkVersion').toInteger()

转到 android/build.gradle

更新 Kotlin 版本

ext.kotlin_version = '1.6.0'

完成后按照创建添加的正常工作