简体   繁体   English

如何在 flutter 应用程序中集成谷歌移动广告

[英]How to integrate google mobile ads in flutter app

Recently flutter announcing the release of Google Mobile Ads for Flutter a new SDK that works with AdMob and AdManager to offer a variety of ad formats, including banner, interstitial, native, and rewarded video ads for flutter Recently flutter announcing the release of Google Mobile Ads for Flutter a new SDK that works with AdMob and AdManager to offer a variety of ad formats, including banner, interstitial, native, and rewarded video ads for flutter

And I want to monetize my flutter app by displaying ads through AdMob.我想通过 AdMob 展示广告来通过我的 flutter 应用获利。 how can we set up and integrate google mobile ads in our flutter app我们如何在我们的 flutter 应用程序中设置和集成谷歌移动广告

The Google Mobile Ads SDK for Flutter currently supports loading and displaying banner, interstitial (full-screen), native ads, and rewarded video ads适用于 Flutter 的 Google 移动广告 SDK 目前支持加载和显示横幅、插页式(全屏)、原生广告和激励视频广告

To Integrating Google Mobile Ads SDK into a Flutter app, which you will do here将 Google 移动广告 SDK 集成到 Flutter 应用程序中,您将在此处执行此操作

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

Adding the Google Mobile Ads plugin as a dependency将 Google Mobile Ads 插件添加为依赖项

add the Google Mobile Ads plugin as a dependency to the pubspec.yaml file located at the root of the project.Google Mobile Ads插件作为依赖项添加到位于项目根目录的pubspec.yaml文件中。

dependencies:
  google_mobile_ads: ^0.11.0+1

Import to in your Dart code, you can use:导入到您的 Dart 代码中,您可以使用:

import 'package:google_mobile_ads/google_mobile_ads.dart';

Setup for Specific Platform特定平台的设置

iOS iOS

Update your Info.plist更新您的Info.plist

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

  2. add a GADApplicationIdentifier key with a string value of your AdMob app ID ( identified in the AdMob UI ) as shown below:添加一个GADApplicationIdentifier键,其字符串值为 AdMob 应用程序 ID(在 AdMob UI 中标识),如下所示:

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

Android Android

Update AndroidManifest.xml更新AndroidManifest.xml

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

  2. Add your AdMob app ID by adding a <meta-data> tag and entering com.google.android.gms.ads.APPLICATION_ID .通过添加<meta-data>标签并输入com.google.android.gms.ads.APPLICATION_ID来添加您的 AdMob 应用 ID。 as shown below.如下所示。 You can find your App ID in the AdMob UI .您可以在AdMob UI中找到您的 App ID。 For android:value insert your own AdMob App ID in quotes, as shown below.对于android:value在引号中插入您自己的 AdMob App 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"/>

The AdMob App ID must be included in the AndroidManifest.xml . AdMob App ID 必须包含在AndroidManifest.xml中。 Failure to do so will result in a crash on the launch of an app.否则将导致应用程序启动时崩溃。

Initialize the Mobile Ads SDK初始化移动广告 SDK

Before loading ads, have your app initialize the Mobile Ads SDK by calling MobileAds.instance.initialize() which initializes the SDK and returns a Future that finishes once initialization is complete (or after a 30-second timeout).在加载广告之前,让您的应用通过调用MobileAds.instance.initialize()来初始化移动广告 SDK,该方法会初始化 SDK 并返回一个在初始化完成后(或在 30 秒超时后)完成的Future This needs to be done only once, ideally right before running the app.这只需要做一次,最好是在运行应用程序之前。

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.
  }
}

Here is an Add a banner ad For all to see googleads-mobile-flutter这是一个添加横幅广告供所有人查看googleads-mobile-flutter

A BannerAd requires an adUnitId, an AdSize, an AdRequest , and an AdListener . BannerAd需要一个 adUnitId、一个 AdSize、一个AdRequest和一个AdListener An example is shown below as well as more information on each parameter follows.下面显示了一个示例,以及有关每个参数的更多信息。

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

To define a custom banner size, set your desired AdSize, as shown here:要定义自定义横幅尺寸,请设置所需的 AdSize,如下所示:

final AdSize adSize = AdSize(300, 50);

Banner Ad Events横幅广告活动

Through the use of AdListener , you can listen for lifecycle events, such as when an ad is closed or the user leaves the app.通过使用AdListener ,您可以监听生命周期事件,例如当广告关闭或用户离开应用程序时。 This example implements each method and logs a message to the console:此示例实现每个方法并将消息记录到控制台:

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.'),
);

After a BannerAd is instantiated, load() must be called before it can be shown on the screen. BannerAd实例化后,必须调用load()才能将其显示在屏幕上。

myBanner.load();

To display a BannerAd as a widget, you must instantiate an AdWidget with a supported ad after calling load().要将BannerAd显示为小部件,您必须在调用 load() 后使用支持的广告实例化AdWidget You can create the widget before calling load() , but load() must be called before adding it to the widget tree.您可以在调用load()之前创建小部件,但在将其添加到小部件树之前必须调用 load( load()

final AdWidget adWidget = AdWidget(ad: myBanner);

AdWidget inherits from Flutter's Widget class and can be used as any other widget. AdWidget继承自 Flutter 的 Widget class,可以作为任何其他的 Widget 使用。 On iOS, make sure you place the widget in a widget with a specified width and height.在 iOS 上,确保将小部件放置在具有指定宽度和高度的小部件中。 Otherwise, your Ad may not be displayed.否则,您的广告可能不会展示。 A BannerAd can be placed in a container with a size that matches the ad: BannerAd可以放置在尺寸与广告匹配的容器中:

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

Finally, release the resource associated with the BannerAd object by calling the BannerAd.dispose() method in the dispose() callback method.最后,在dispose()回调方法中调用BannerAd.dispose()方法释放BannerAd对象关联的资源。

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

That's it.而已。 Your app is now ready to display banner ads.您的应用现在可以显示横幅广告了。

Full Example完整示例

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

在此处输入图像描述

Step 1: Add dependencies to pubspec.yaml第 1 步:将依赖项添加到 pubspec.yaml

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2

  google_mobile_ads: ^0.13.0 #this

Step 2: Update your Info.plist in IOS and Update AndroidManifest.xml in Android第 2 步:更新 IOS 中的 Info.plist 并更新 Android 中的 AndroidManifest.xml

For IOS对于 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>

For Android适用于 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>

Step 2:Initialize the Mobile Ads SDK in main.dart第 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());
}

Step 4:Create Ad Units in Admob then we are ready to implement ads第 4 步:在 Admob 中创建广告单元,然后我们就可以实施广告了

Step 5:Make sure you enable multidex in app/build.gradle file第 5 步:确保在 app/build.gradle 文件中启用 multidex

defaultConfig {
        ....
        multiDexEnabled true
    }

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

Step 6: Create admanager.dart file第六步:创建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);

Step 7: Now go to home page use it第 7 步:现在 go 到主页使用它

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,
                    ],
                  ),
               ),
            );
  }
}

Thanks谢谢

flutter 2.8 adding of Google Admobs flutter 2.8 添加 Google Admobs

Add dependencies添加依赖项

google_mobile_ads: ^1.0.1 google_mobile_ads:^1.0.1

Import进口

import 'package:google_mobile_ads/google_mobile_ads.dart';导入“包:google_mobile_ads/google_mobile_ads.dart”;

Go to android/local.properties and add versions Go 到 android/local.properties 并添加版本

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

Goto android/app/build.gradle and add转到 android/app/build.gradle 并添加

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

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

Goto android/build.gradle转到 android/build.gradle

Update the Kotlin version更新 Kotlin 版本

ext.kotlin_version = '1.6.0' ext.kotlin_version = '1.6.0'

Once done follow the normal working of creating the adds完成后,按照创建添加的正常工作

Good thing there is an existing documentation for Ads support for Flutter .好消息是现有的 Flutter 的广告支持文档。

Monetizing apps by using ads has been one of the most popular requests for many Flutter developers.通过使用广告从应用程序中获利一直是许多 Flutter 开发人员最受欢迎的请求之一。

Flutter ads support is available through the Google Mobile Ads SDK for Flutter (Beta) , which works with both AdMob and AdManager. Flutter 广告支持可通过Google 移动广告 SDK 获得,适用于 Flutter(测试版) ,适用于 Z61DDE80618C83306F6E 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:以下视频教程,使用 Flutter 为应用获利,展示了如何开始使用广告:

The following resources can help you get started:以下资源可以帮助您入门:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM