Google 移动广告 Flutter 版
本指南适用于希望通过 Flutter 应用获利的发布商。
将 Google 移动广告 SDK 集成到 Flutter 应用中(您将在此处完成)是展示 AdMob 广告并赚取收入的第一步。集成完成后,您可以选择一种广告格式以获取详细的实现步骤。
Google 移动广告 Flutter 版 SDK 目前支持加载和展示横幅广告、插页式广告(全屏广告)、原生广告和激励视频广告。
注意:此插件还支持 Google Ad Manager。如果您有兴趣使用 Ad Manager 创建和加载广告,可以遵循本说明文档中概述的相同前提条件、平台设置、移动广告 SDK 初始化步骤,然后参阅 使用 Ad Manager 创建和加载广告 以获取进一步说明。
另请参阅 Flutter 中的内嵌广告 Codelab,其中提供了关于设置
内嵌横幅广告和原生广告的详细指南。
先决条件
- Flutter 1.22.0 或更高版本
- Android
- Android Studio 3.2 或更高版本
- 目标 Android API 级别 19 或更高版本
- 将
compileSdkVersion设置为 28 或更高版本 - Android Gradle 插件 4.1 或更高版本(这是 Flutter 开箱即用的支持版本)
- iOS
- 最新版本的 Xcode,并已启用命令行工具。
- 建议:创建 AdMob 帐号并注册 Android 和/或 iOS 应用(要在已发布的应用中展示真实广告,必须注册该应用)。
导入移动广告 SDK
- 将 Google 移动广告 Flutter 版 SDK 添加到您的 Flutter 项目中。
平台特定设置
iOS
更新 Info.plist
更新应用的 ios/Runner/Info.plist 文件,添加两个键:
- 一个
GADApplicationIdentifier键,其字符串值为您的 AdMob 应用 ID(在 AdMob UI 中标识)。 - 一个
SKAdNetworkItems键,其中包含 Google 的SKAdNetworkIdentifier值cstr6suwn9.skadnetwork。
<key>GADApplicationIdentifier</key>
<string>ca-app-pub-3940256099942544~1458002511</string>
<key>SKAdNetworkItems</key>
<array>
<dict>
<key>SKAdNetworkIdentifier</key>
<string>cstr6suwn9.skadnetwork</string>
</dict>
</array>
有关配置 Info.plist 和设置您的应用 ID 的详细信息,请参阅 https://developers.google.com/admob/ios/quick-start#update_your_infoplist。
Android
更新 AndroidManifest.xml
AdMob 应用 ID 必须包含在 AndroidManifest.xml 文件中。否则,应用启动时将崩溃。
通过添加一个名为 com.google.android.gms.ads.APPLICATION_ID 的 <meta-data> 标签,将 AdMob 应用 ID(在 AdMob UI 中标识)添加到应用的 android/app/src/main/AndroidManifest.xml 文件中,如下所示。您可以在 AdMob UI 中找到您的应用 ID。对于 android:value,请在引号中插入您自己的 AdMob 应用 ID,如下所示。
<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>
在 Dart 代码中初始化插件时使用相同的值。
有关配置 AndroidManifest.xml 和设置应用 ID 的详细信息,请参阅 https://goo.gl/fQ2neu。
初始化移动广告 SDK
在加载广告之前,请通过调用 MobileAds.instance.initialize() 来初始化移动广告 SDK。此方法初始化 SDK 并返回一个 Future,该 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.
}
}
选择广告格式
移动广告 SDK 现已导入,您可以开始实现广告了。AdMob 提供多种广告格式,您可以选择最适合您应用用户体验的格式。
- 横幅
- 以矩形形式出现在设备屏幕顶部或底部的广告。横幅广告在用户与应用互动时会一直显示在屏幕上,并且可以在一段时间后自动刷新。如果您是移动广告新手,横幅广告是很好的起点。
- 插页式广告
- 全屏广告,会覆盖应用界面,直到用户关闭。它们最适合在应用执行流程中的自然停顿点展示,例如游戏关卡之间或任务完成后。
- 原生广告
- 可自定义的广告,可匹配您应用的外观和感觉。您可以决定如何以及在何处放置它们,因此布局与您应用的设计更加一致。
- 激励广告
- 奖励用户观看短视频并与可玩广告和调查互动的广告。适合为免费游戏用户创收。
横幅广告
横幅广告会占据应用布局中的一个位置,通常在设备屏幕的顶部或底部。它们在用户与应用互动时会一直显示在屏幕上,并可以在一段时间后自动刷新。
本指南将向您展示如何将 AdMob 的横幅广告集成到 Flutter 应用中。除了代码片段和说明外,它还包含有关正确调整横幅广告大小的信息以及指向其他资源的链接。
另请参阅 Flutter 中的内嵌广告 Codelab,其中提供了关于设置横幅广告的详细指南。
始终使用测试广告进行测试
在构建和测试您的应用时,请务必使用测试广告而不是真实、生产中的广告。否则,您的帐号可能会被暂停。
加载测试广告的最简单方法是使用我们专用的横幅广告测试广告单元 ID。
- Android:https://developers.google.com/admob/android/test-ads#sample_ad_units
- iOS:https://developers.google.com/admob/ios/test-ads#demo_ad_units
它经过专门配置,可以为每个请求返回测试广告,您可以在编码、测试和调试时随意在自己的应用中使用它。只需确保在发布应用之前将其替换为您自己的广告单元 ID。
实例化横幅广告
BannerAd 需要 adUnitId、AdSize、AdRequest 和 BannerAdListener。下面提供了一个示例,以及有关每个参数的更多信息。
final BannerAd myBanner = BannerAd(
adUnitId: '<ad unit id>',
size: AdSize.banner,
request: AdRequest(),
listener: BannerAdListener(),
);
横幅广告尺寸
下表列出了标准的横幅广告尺寸。
| 尺寸(dp,宽x高) | 描述 | AdSize 常量 |
| 320x50 | 标准横幅广告 | banner
|
| 320x100 | 大型横幅广告 | largeBanner
|
| 320x250 | 中型矩形 | mediumRectangle
|
| 468x60 | 全尺寸横幅广告 | fullBanner
|
| 728x90 | 排行榜 | leaderboard
|
| 屏幕宽度 x 32|50|90 | 智能横幅广告 | 使用 getSmartBanner(Orientation) |
| 提供的宽度 x 自适应高度 | 自适应横幅广告 | 使用 getAnchoredAdaptiveBannerAdSize(Orientation, int) |
要定义自定义横幅广告尺寸,请设置所需的 AdSize,如下所示。
final AdSize adSize = AdSize(300, 50);
横幅广告事件
通过使用 BannerAdListener,您可以监听生命周期事件,例如广告加载时。此示例实现了每个方法并将消息记录到控制台。
final BannerAdListener listener = BannerAdListener(
// Called when an ad is successfully received.
onAdLoaded: (Ad ad) => print('Ad loaded.'),
// Called when an ad request failed.
onAdFailedToLoad: (Ad ad, LoadAdError error) {
// Dispose the ad here to free resources.
ad.dispose();
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 impression occurs on the ad.
onAdImpression: (Ad ad) => print('Ad impression.'),
);
加载横幅广告
实例化 BannerAd 后,必须先调用 load() 才能将其显示在屏幕上。
myBanner.load();
显示横幅广告
要将 BannerAd 显示为小部件,您必须在调用 load() 后实例化一个支持广告的 AdWidget。您可以在调用 load() 之前创建小部件,但必须在将小部件添加到小部件树之前调用 load()。
final AdWidget adWidget = AdWidget(ad: myBanner);
AdWidget 继承自 Flutter 的 Widget 类,可以像任何其他小部件一样使用。在 iOS 上,请确保将小部件放置在一个具有指定宽度和高度的小部件中。否则,您的广告可能不会显示。BannerAd 可以放置在一个大小与广告匹配的容器中。
final Container adContainer = Container(
alignment: Alignment.center,
child: adWidget,
width: myBanner.size.width.toDouble(),
height: myBanner.size.height.toDouble(),
);
一旦广告调用了 load(),当不再需要访问该广告时,它必须调用 dispose()。调用 dispose() 的最佳实践是在 AdWidget 从小部件树中移除后,或在 AdListener.onAdFailedToLoad 回调中。
这样就完成了!您的应用现在可以展示横幅广告了。
插页式广告
插页式广告是全屏广告,会覆盖其托管应用的用户界面。它们通常在应用的自然过渡点显示,例如活动之间或游戏关卡之间的暂停期间。当应用显示插页式广告时,用户可以选择点按广告并继续前往其目的地,或关闭广告并返回到应用。
本指南将介绍如何将插页式广告集成到 Flutter 应用中。
始终使用测试广告进行测试
在构建和测试您的应用时,请务必使用测试广告而不是真实、生产中的广告。否则,您的帐号可能会被暂停。
加载插页式广告的最简单方法是使用我们专用的插页式广告测试广告单元 ID。
- Android:https://developers.google.com/admob/android/test-ads#sample_ad_units
- iOS:https://developers.google.com/admob/ios/test-ads#demo_ad_units
它经过专门配置,可以为每个请求返回测试广告,您可以在编码、测试和调试时随意在自己的应用中使用它。只需确保在发布应用之前将其替换为您自己的广告单元 ID。
加载插页式广告
加载 InterstitialAd 需要 adUnitId、AdRequest 和 InterstitialAdLoadCallback。下面提供了一个示例,以及有关每个参数的更多信息。
InterstitialAd.load(
adUnitId: '<ad unit id>',
request: AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: (InterstitialAd ad) {
// Keep a reference to the ad so you can show it later.
this._interstitialAd = ad;
},
onAdFailedToLoad: (LoadAdError error) {
print('InterstitialAd failed to load: $error');
},
));
插页式广告事件
通过使用 FullScreenContentCallback,您可以监听生命周期事件,例如广告显示或关闭时。
在展示广告之前设置 InterstitialAd.fullScreenContentCallback 以接收这些事件的通知。此示例实现了每个方法并将消息记录到控制台。
interstitialAd.fullScreenContentCallback = FullScreenContentCallback(
onAdShowedFullScreenContent: (InterstitialAd ad) =>
print('$ad onAdShowedFullScreenContent.'),
onAdDismissedFullScreenContent: (InterstitialAd ad) {
print('$ad onAdDismissedFullScreenContent.');
ad.dispose();
},
onAdFailedToShowFullScreenContent: (InterstitialAd ad, AdError error) {
print('$ad onAdFailedToShowFullScreenContent: $error');
ad.dispose();
},
onAdImpression: (InterstitialAd ad) => print('$ad impression occurred.'),
);
显示插页式广告
InterstitialAd 显示为覆盖在所有应用内容之上的叠加层,并且是静态放置的。这意味着它不能添加到 Flutter 小部件树中。您可以通过调用 show() 来选择何时展示广告。
myInterstitial.show();
调用 show() 后,以这种方式显示的广告无法以编程方式移除,需要用户输入。InterstitialAd 只能显示一次。后续的 show 调用将触发 onAdFailedToShowFullScreenContent。
一旦广告调用了 load(),当不再需要访问该广告时,它必须调用 dispose()。调用 dispose() 的最佳实践是在 FullScreenContentCallback.onAdDismissedFullScreenContent 和 FullScreenContentCallback.onAdFailedToShowFullScreenContent 回调中。
这样就完成了!您的应用现在可以展示插页式广告了。
后续步骤
原生广告
原生广告是通过平台原生 UI 组件呈现给用户的广告素材。它们使用您已用于构建布局的相同类型的视图展示,并且可以格式化以匹配其所在用户体验的视觉设计。在编码方面,这意味着当原生广告加载时,您的应用会收到一个包含其素材资源的 NativeAd 对象,然后由应用(而不是 Google 移动广告 SDK)负责展示它们。
总的来说,成功实现原生广告有两个方面:通过 SDK 加载广告和展示广告内容。本指南着重于使用 SDK 加载原生广告。
另请参阅 Flutter 中的内嵌广告 Codelab,其中提供了关于设置原生广告的详细指南。
平台设置
原生广告通过平台原生 UI 组件呈现给用户。(例如,Android 上的 View 或 iOS 上的 UIView)。
由于原生广告需要平台原生 UI 组件,因此此功能需要为 Android 和 iOS 进行额外设置。
Android
Google 移动广告插件的 Android 实现需要一个实现 NativeAdFactory 的类。NativeAdFactory 包含一个方法,该方法接受一个 NativeAd 和自定义选项,并返回一个 NativeAdView。NativeAdView 将在您的应用中显示。
您可以在 MainActivity.java 中实现此功能,或在与 MainActivity.java 相同的目录中创建一个单独的类,如下所示。
package my.app.path;
import com.google.android.gms.ads.nativead.NativeAd;
import com.google.android.gms.ads.nativead.NativeAdView;
import io.flutter.plugins.googlemobileads.GoogleMobileAdsPlugin.NativeAdFactory;
import java.util.Map;
class NativeAdFactoryExample implements NativeAdFactory {
@Override
public NativeAdView createNativeAd(
NativeAd nativeAd, Map<String, Object> customOptions) {
// Create NativeAdView
}
}
每个 NativeAdFactory 都需要在 MainActivity.configureFlutterEngine(FlutterEngine) 中使用唯一的 String 标识符 factoryId 进行注册。NativeAdFactory 可以为应用使用的每个唯一的原生广告布局实现和注册,或者一个可以处理所有布局。构建 add-to-app 时,还应在 cleanUpFlutterEngine(engine) 中注销 NativeAdFactory。
MainActivity.java 应如下所示:
package my.app.path;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.googlemobileads.GoogleMobileAdsPlugin;
public class MainActivity extends FlutterActivity {
@Override
public void configureFlutterEngine(FlutterEngine flutterEngine) {
flutterEngine.getPlugins().add(new GoogleMobileAdsPlugin());
super.configureFlutterEngine(flutterEngine);
GoogleMobileAdsPlugin.registerNativeAdFactory(flutterEngine, "adFactoryExample", NativeAdFactoryExample());
}
@Override
public void cleanUpFlutterEngine(FlutterEngine flutterEngine) {
GoogleMobileAdsPlugin.unregisterNativeAdFactory(flutterEngine, "adFactoryExample");
}
}
在 Dart 中创建 NativeAd 时,factoryId 需要与用于将工厂添加到 GoogleMobileAdsPlugin 的 factoryId 匹配。在上面的代码片段中,adFactoryExample 是 factoryId 的名称。下面是一个 NativeAdFactory 示例。
package io.flutter.plugins.googlemobileadsexample;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.widget.TextView;
import com.google.android.gms.ads.nativead.NativeAd;
import com.google.android.gms.ads.nativead.NativeAdView;
import io.flutter.plugins.googlemobileads.GoogleMobileAdsPlugin.NativeAdFactory;
import java.util.Map;
// my_native_ad.xml can be found at
/* https://github.com/googleads/googleads-mobile-flutter/tree/master/packages/google_mobile_ads/example/android/app/src/main/res/layout
*/
class NativeAdFactoryExample implements NativeAdFactory {
private final LayoutInflater layoutInflater;
NativeAdFactoryExample(LayoutInflater layoutInflater) {
this.layoutInflater = layoutInflater;
}
@Override
public NativeAdView createNativeAd(
NativeAd nativeAd, Map<String, Object> customOptions) {
final NativeAdView adView =
(NativeAdView) layoutInflater.inflate(R.layout.my_native_ad, null);
final TextView headlineView = adView.findViewById(R.id.ad_headline);
final TextView bodyView = adView.findViewById(R.id.ad_body);
headlineView.setText(nativeAd.getHeadline());
bodyView.setText(nativeAd.getBody());
adView.setBackgroundColor(Color.YELLOW);
adView.setNativeAd(nativeAd);
adView.setBodyView(bodyView);
adView.setHeadlineView(headlineView);
return adView;
}
}
iOS
Google 移动广告插件的 iOS 实现需要一个实现 FLTNativeAdFactory 的类。FLTNativeAdFactory 包含一个方法,该方法接受一个 GADNativeAd 和自定义选项,并返回一个 GADNativeAdView。GADNativeAdView 将在您的应用中显示。
FLTNativeAdFactory 协议可以由 AppDelegate 实现,或者可以创建一个单独的类,如下所示。
/* AppDelegate.m */
#import "FLTGoogleMobileAdsPlugin.h"
@interface NativeAdFactoryExample : NSObject<FLTNativeAdFactory>
@end
@implementation NativeAdFactoryExample
- (GADNativeAdView *)createNativeAd:(GADNativeAd *)nativeAd
customOptions:(NSDictionary *)customOptions {
// Create GADNativeAdView
}
@end
每个 FLTNativeAdFactory 都需要在 registerNativeAdFactory:factoryId:nativeAdFactory: 中使用唯一的 String 标识符 factoryId 进行注册。FLTNativeAdFactory 可以为应用使用的每个唯一的原生广告布局实现和注册,或者一个可以处理所有布局。这可以通过导入 FLTGoogleMobileAdsPlugin.h 并使用 FlutterPluginRegistry、工厂的唯一标识符以及工厂本身调用 registerNativeAdFactory:factoryId:nativeAdFactory: 来完成。在调用 [GeneratedPluginRegistrant registerWithRegistry:self]; 之后,还必须添加工厂。
如果此操作在 AppDelegate.m 中完成,应如下所示:
#import "FLTGoogleMobileAdsPlugin.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
NativeAdFactoryExample *nativeAdFactory = [[NativeAdFactoryExample alloc] init];
[FLTGoogleMobileAdsPlugin registerNativeAdFactory:self
factoryId:@"adFactoryExample"
nativeAdFactory:nativeAdFactory];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
在 Dart 中创建 NativeAd 时,factoryID 需要与用于将工厂添加到 FLTGoogleMobileAdsPlugin 的 factoryID 匹配。在上面的代码片段中,adFactoryExample 是 factoryID 的名称。下面是一个 FLTNativeAdFactory 示例。
// The example NativeAdView.xib can be found at
/* https://github.com/googleads/googleads-mobile-flutter/blob/master/packages/google_mobile_ads/example/ios/Runner/NativeAdView.xib
*/
@interface NativeAdFactoryExample : NSObject <FLTNativeAdFactory>
@end
@implementation NativeAdFactoryExample
- (GADNativeAdView *)createNativeAd:(GADNativeAd *)nativeAd
customOptions:(NSDictionary *)customOptions {
// Create and place ad in view hierarchy.
GADNativeAdView *adView =
[[NSBundle mainBundle] loadNibNamed:@"NativeAdView" owner:nil options:nil].firstObject;
// Associate the native ad view with the native ad object. This is
// required to make the ad clickable.
adView.nativeAd = nativeAd;
// Populate the native ad view with the native ad assets.
// The headline is guaranteed to be present in every native ad.
((UILabel *)adView.headlineView).text = nativeAd.headline;
// These assets are not guaranteed to be present. Check that they are before
// showing or hiding them.
((UILabel *)adView.bodyView).text = nativeAd.body;
adView.bodyView.hidden = nativeAd.body ? NO : YES;
[((UIButton *)adView.callToActionView) setTitle:nativeAd.callToAction
forState:UIControlStateNormal];
adView.callToActionView.hidden = nativeAd.callToAction ? NO : YES;
((UIImageView *)adView.iconView).image = nativeAd.icon.image;
adView.iconView.hidden = nativeAd.icon ? NO : YES;
((UILabel *)adView.storeView).text = nativeAd.store;
adView.storeView.hidden = nativeAd.store ? NO : YES;
((UILabel *)adView.priceView).text = nativeAd.price;
adView.priceView.hidden = nativeAd.price ? NO : YES;
((UILabel *)adView.advertiserView).text = nativeAd.advertiser;
adView.advertiserView.hidden = nativeAd.advertiser ? NO : YES;
// In order for the SDK to process touch events properly, user interaction
// should be disabled.
adView.callToActionView.userInteractionEnabled = NO;
return adView;
}
@end
始终使用测试广告进行测试
在构建和测试您的应用时,请务必使用测试广告而不是真实、生产中的广告。否则,您的帐号可能会被暂停。
加载原生广告的最简单方法是使用我们专用的原生广告测试广告单元 ID。
- Android:https://developers.google.com/admob/android/test-ads#sample_ad_units
- iOS:https://developers.google.com/admob/ios/test-ads#demo_ad_units
它经过专门配置,可以为每个请求返回测试广告,您可以在编码、测试和调试时随意在自己的应用中使用它。只需确保在发布应用之前将其替换为您自己的广告单元 ID。
实例化原生广告
NativeAd 需要 adUnitId、factoryId、AdRequest 和 NativeAdListener。下面提供了一个示例,以及有关每个参数的更多信息。
final NativeAd myNative = NativeAd(
adUnitId: '<test id or account id>',
factoryId: 'adFactoryExample',
request: AdRequest(),
listener: NativeAdListener(),
);
工厂 ID
factoryId 需要与用于将工厂添加到 Android 上的 GoogleMobileAdsPlugin 和/或 iOS 上的 FLTGoogleMobileAdsPlugin 的 factoryId 匹配。两个平台可以使用相同的 factoryId,或者每个平台都可以有自己的。
原生广告事件
通过使用 NativeAdListener,您可以监听生命周期事件,例如广告关闭或用户离开应用时。此示例实现了每个方法并将消息记录到控制台。
final NativeAdListener listener = NativeAdListener(
// Called when an ad is successfully received.
onAdLoaded: (Ad ad) => print('Ad loaded.'),
// Called when an ad request failed.
onAdFailedToLoad: (Ad ad, LoadAdError error) {
// Dispose the ad here to free resources.
ad.dispose();
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 impression occurs on the ad.
onAdImpression: (Ad ad) => print('Ad impression.'),
// Called when a click is recorded for a NativeAd.
onNativeAdClicked: (NativeAd ad) => print('Ad clicked.'),
);
NativeAdOptions
NativeAds 有一个可选参数 nativeAdOptions,可用于为原生广告设置特定选项。
shouldReturnUrlsForImageAssets
如果设置为 `true`,SDK 将不会加载图片素材内容,并且可以使用原生广告图片 URL 来获取内容。默认为 false。
shouldRequestMultipleImages
某些图片素材资源包含一系列图片,而不仅仅是一张。将此值设置为 true,您的应用即表示已准备好显示任何包含多张图片的素材资源。将其设置为 false(默认值)会指示 SDK 仅提供包含一系列图片的第一个图片素材资源。
如果在初始化 NativeAd 时未传递任何 NativeadOptions,则将使用每个属性的默认值。
adChoicesPlacement
默认情况下,[AdChoices 叠加层](https://developers.google.com/admob/android/native/advanced#adchoices_overlay)设置在右上方。应用可以通过将此属性设置为以下选项之一来更改叠加层渲染的角落:
- AdChoicesPlacement.topLeftCorner
- AdChoicesPlacement.topLeftCorner
- AdChoicesPlacement.bottomRightCorner
- AdChoicesPlacement.bottomLeftCorner
videoOptions
可用于为作为原生广告一部分返回的视频素材资源设置视频选项。
mediaAspectRatio
这会设置要为原生广告返回的图片或视频的纵横比。将 NativeMediaAspectRatio 设置为以下常量之一将仅返回指定纵横比媒体的广告:
- MediaAspectRatio.landscape
- MediaAspectRatio.portrait
- MediaAspectRatio.square
- MediaAspectRatio.any
如果未设置,将返回任何纵横比的广告。
加载原生广告
实例化 NativeAd 后,必须先调用 load() 才能将其显示在屏幕上。
myNative.load();
显示原生广告
要将 NativeAd 显示为小部件,您必须在调用 load() 后实例化一个支持广告的 AdWidget。您可以在调用 load() 之前创建小部件,但必须在将小部件添加到小部件树之前调用 load()。
final AdWidget adWidget = AdWidget(ad: myBanner);
AdWidget 继承自 Flutter 的 Widget 类,可以像任何其他小部件一样使用。在 iOS 上,请确保将小部件放置在一个具有指定宽度和高度的小部件中。否则,您的广告可能不会显示。
final Container adContainer = Container(
alignment: Alignment.center,
child: adWidget,
width: 500,
height: 500,
);
一旦广告调用了 load(),当不再需要访问该广告时,它必须调用 dispose()。调用 dispose() 的最佳实践是在 AdWidget 从小部件树中移除后,或在 AdListener.onAdFailedToLoad 回调中。
这样就完成了!您的应用现在可以展示原生广告了。
后续步骤
激励广告
激励广告是用户可以选择互动以换取应用内奖励的广告。本指南将向您展示如何将 AdMob 的激励广告集成到 Flutter 应用中。
始终使用测试广告进行测试
在构建和测试您的应用时,请务必使用测试广告而不是真实、生产中的广告。否则,您的帐号可能会被暂停。
加载激励广告的最简单方法是使用我们专用的激励广告测试广告单元 ID。
- Android:https://developers.google.com/admob/android/test-ads#sample_ad_units
- iOS:https://developers.google.com/admob/ios/test-ads#demo_ad_units
它经过专门配置,可以为每个请求返回测试广告,您可以在编码、测试和调试时随意在自己的应用中使用它。只需确保在发布应用之前将其替换为您自己的广告单元 ID。
加载激励广告
加载 RewardedAd 需要 adUnitId、AdRequest 和 RewardedAdLoadCallback。下面提供了一个示例,以及有关每个参数的更多信息。
RewardedAd.load(
adUnitId: '<test id or account id>',
request: AdRequest(),
rewardedAdLoadCallback: RewardedAdLoadCallback(
onAdLoaded: (RewardedAd ad) {
print('$ad loaded.');
// Keep a reference to the ad so you can show it later.
this._rewardedAd = ad;
},
onAdFailedToLoad: (LoadAdError error) {
print('RewardedAd failed to load: $error');
},
);
激励广告事件
通过使用 FullScreenContentCallback,您可以监听生命周期事件,例如广告显示或关闭时。
在展示广告之前设置 RewardedAd.fullScreenContentCallback 以接收这些事件的通知。此示例实现了每个方法并将消息记录到控制台。
rewardedAd.fullScreenContentCallback = FullScreenContentCallback(
onAdShowedFullScreenContent: (RewardedAd ad) =>
print('$ad onAdShowedFullScreenContent.'),
onAdDismissedFullScreenContent: (RewardedAd ad) {
print('$ad onAdDismissedFullScreenContent.');
ad.dispose();
},
onAdFailedToShowFullScreenContent: (RewardedAd ad, AdError error) {
print('$ad onAdFailedToShowFullScreenContent: $error');
ad.dispose();
},
onAdImpression: (RewardedAd ad) => print('$ad impression occurred.'),
);
显示激励广告
RewardedAd 显示为覆盖在所有应用内容之上的叠加层,并且是静态放置的。这意味着它不能以这种方式添加到 Flutter 小部件树中。您可以通过调用 show() 来选择何时展示广告。
RewardedAd.show() 接受一个 OnUserEarnedRewardCallback,当用户获得奖励时会调用该回调。请务必实现此功能并奖励用户观看广告。
myRewarded.show(onUserEarnedReward: (RewardedAd ad, RewardItem rewardItem) {
// Reward the user for watching an ad.
});
调用 show() 后,以这种方式显示的广告无法以编程方式移除,需要用户输入。RewardedAd 只能显示一次。后续的 show 调用将触发 onAdFailedToShowFullScreenContent。
一旦广告调用了 load(),当不再需要访问该广告时,它必须调用 dispose()。调用 dispose() 的最佳实践是在 FullScreenContentCallback.onAdDismissedFullScreenContent 和 FullScreenContentCallback.onAdFailedToShowFullScreenContent 回调中。
这样就完成了!您的应用现在可以展示激励广告了。
使用 Ad Manager 创建和加载广告
本节介绍如何使用 Google Ad Manager 创建和加载广告。
选择广告格式
- 横幅
- 以矩形形式出现在设备屏幕顶部或底部的广告。横幅广告在用户与应用互动时会一直显示在屏幕上,并且可以在一段时间后自动刷新。如果您是移动广告新手,横幅广告是很好的起点。
- 插页式广告
- 全屏广告,会覆盖应用界面,直到用户关闭。它们最适合在应用执行流程中的自然停顿点展示,例如游戏关卡之间或任务完成后。
- 原生广告
- 可自定义的广告,可匹配您应用的外观和感觉。您可以决定如何以及在何处放置它们,因此布局与您应用的设计更加一致。
- 激励广告
- 奖励用户观看短视频并与可玩广告和调查互动的广告。适合为免费游戏用户创收。
AdManagerAdRequest
对于 Ad Manager,您将使用 AdManagerAdRequest 而不是 AdRequest。
AdManagerAdRequest 类似于 AdRequest,但有两个额外的属性:customTargeting 和 customTargetingLists,
它们用于支持自定义定位。
final AdManagerAdRequest request = AdManagerAdRequest(
keywords: <String>['flutterio', 'beautiful apps'],
contentUrl: 'https://flutterdart.cn',
customTargeting: <String, String>{'some': 'targeting'},
customTargetingLists: <String, List<String>>{'favoriteColors': <String>['red', 'yellow']},
);
Ad Manager 横幅广告
横幅广告会占据应用布局中的一个位置,通常在设备屏幕的顶部或底部。它们在用户与应用互动时会一直显示在屏幕上,并可以在一段时间后自动刷新。
本指南将向您展示如何将 Ad Manager 的横幅广告集成到 Flutter 应用中。除了代码片段和说明外,它还包含有关正确调整横幅广告大小的信息以及指向其他资源的链接。
另请参阅 Flutter 中的内嵌广告 Codelab,其中提供了关于设置横幅广告的详细指南。
始终使用测试广告进行测试
在构建和测试您的应用时,请务必使用测试广告而不是真实、生产中的广告。否则,您的帐号可能会被暂停。
加载测试广告的最简单方法是使用我们专用的横幅广告测试广告单元 ID。
- Android:https://developers.google.com/ad-manager/mobile-ads-sdk/android/test-ads#sample_ad_units
- iOS:https://developers.google.com/ad-manager/mobile-ads-sdk/ios/test-ads#demo_ad_units
它经过专门配置,可以为每个请求返回测试广告,您可以在编码、测试和调试时随意在自己的应用中使用它。只需确保在发布应用之前将其替换为您自己的广告单元 ID。
实例化横幅广告
AdManagerBannerAd 需要 adUnitId、AdSize、AdRequest 和 AdListener。下面提供了一个示例,以及有关每个参数的更多信息。
final AdManagerBannerAd myBanner = AdManagerBannerAd(
adUnitId: '<ad unit id>',
size: AdSize.banner,
request: AdManagerAdRequest(),
listener: AdManagerBannerAdListener(),
);
横幅广告尺寸
下表列出了标准的横幅广告尺寸。
| 尺寸(dp,宽x高) | 描述 | AdSize 常量 |
| 320x50 | 标准横幅广告 | banner
|
| 320x100 | 大型横幅广告 | largeBanner
|
| 320x250 | 中型矩形 | mediumRectangle
|
| 468x60 | 全尺寸横幅广告 | fullBanner
|
| 728x90 | 排行榜 | leaderboard
|
| 屏幕宽度 x 32|50|90 | 智能横幅广告 | 使用 getSmartBanner(Orientation) |
要定义自定义横幅广告尺寸,请设置所需的 AdSize,如下所示。
final AdSize adSize = AdSize(300, 50);
横幅广告事件
通过使用 AdManagerBannerAdListener,您可以监听生命周期事件,例如广告关闭时。此示例实现了每个方法并将消息记录到控制台。
final AdManagerBannerAdListener listener = AdManagerBannerAdListener(
// Called when an ad is successfully received.
onAdLoaded: (Ad ad) => print('Ad loaded.'),
// Called when an ad request failed.
onAdFailedToLoad: (Ad ad, LoadAdError error) {
// Dispose the ad here to free resources.
ad.dispose();
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 impression occurs on the ad.
onAdImpression: (Ad ad) => print('Ad impression.'),
);
加载横幅广告
实例化 AdManagerBannerAd 后,必须先调用 load() 才能将其显示在屏幕上。
myBanner.load();
显示横幅广告
要将 AdManagerBannerAd 显示为小部件,您必须在调用 load() 后实例化一个支持广告的 AdWidget。您可以在调用 load() 之前创建小部件,但必须在将小部件添加到小部件树之前调用 load()。
final AdWidget adWidget = AdWidget(ad: myBanner);
AdWidget 继承自 Flutter 的 Widget 类,可以像任何其他小部件一样使用。在 iOS 上,请确保将小部件放置在一个具有指定宽度和高度的小部件中。否则,您的广告可能不会显示。AdManagerBannerAd 可以放置在一个大小与广告匹配的容器中。
final Container adContainer = Container(
alignment: Alignment.center,
child: adWidget,
width: myBanner.size.width.toDouble(),
height: myBanner.size.height.toDouble(),
);
一旦广告调用了 load(),当不再需要访问该广告时,它必须调用 dispose()。调用 dispose() 的最佳实践是在 AdWidget 从小部件树中移除后,或在 AdManagerBannerAdListener.onAdFailedToLoad 回调中。
这样就完成了!您的应用现在可以展示横幅广告了。
Ad Manager 插页式广告
插页式广告是全屏广告,会覆盖其托管应用的用户界面。它们通常在应用的自然过渡点显示,例如活动之间或游戏关卡之间的暂停期间。当应用显示插页式广告时,用户可以选择点按广告并继续前往其目的地,或关闭广告并返回到应用。
本指南将介绍如何将插页式广告集成到 Flutter 应用中。
始终使用测试广告进行测试
在构建和测试您的应用时,请务必使用测试广告而不是真实、生产中的广告。否则,您的帐号可能会被暂停。
加载插页式广告的最简单方法是使用我们专用的插页式广告测试广告单元 ID。
- Android:https://developers.google.com/ad-manager/mobile-ads-sdk/android/test-ads#sample_ad_units
- iOS:https://developers.google.com/ad-manager/mobile-ads-sdk/ios/test-ads#demo_ad_units
它经过专门配置,可以为每个请求返回测试广告,您可以在编码、测试和调试时随意在自己的应用中使用它。只需确保在发布应用之前将其替换为您自己的广告单元 ID。
加载插页式广告
加载 AdManagerInterstitialAd 需要 adUnitId、AdRequest 和 AdManagerInterstitialAdLoadCallback。下面提供了一个示例,以及有关每个参数的更多信息。
AdManagerInterstitialAd.load(
adUnitId: '<ad unit id>',
request: AdRequest(),
adLoadCallback: AdManagerInterstitialAdLoadCallback(
onAdLoaded: (AdManagerInterstitialAd ad) {
// Keep a reference to the ad so you can show it later.
this._interstitialAd = ad;
},
onAdFailedToLoad: (LoadAdError error) {
print('InterstitialAd failed to load: $error');
},
));
插页式广告事件
通过使用 FullScreenContentCallback,您可以监听生命周期事件,例如广告显示或关闭时。
在展示广告之前设置 AdManagerInterstitialAd.fullScreenContentCallback 以接收这些事件的通知。此示例实现了每个方法并将消息记录到控制台。
interstitialAd.fullScreenContentCallback = FullScreenContentCallback(
onAdShowedFullScreenContent: (InterstitialAd ad) =>
print('$ad onAdShowedFullScreenContent.'),
onAdDismissedFullScreenContent: (InterstitialAd ad) {
print('$ad onAdDismissedFullScreenContent.');
ad.dispose();
},
onAdFailedToShowFullScreenContent: (InterstitialAd ad, AdError error) {
print('$ad onAdFailedToShowFullScreenContent: $error');
ad.dispose();
},
onAdImpression: (InterstitialAd ad) => print('$ad impression occurred.'),
);
显示插页式广告
AdManagerInterstitialAd 显示为覆盖在所有应用内容之上的叠加层,并且是静态放置的。这意味着它不能添加到 Flutter 小部件树中。您可以通过调用 show() 来选择何时展示广告。
myInterstitial.show();
调用 show() 后,以这种方式显示的广告无法以编程方式移除,需要用户输入。InterstitialAd 只能显示一次。后续的 show 调用将触发 onAdFailedToShowFullScreenContent。
一旦广告调用了 load(),当不再需要访问该广告时,它必须调用 dispose()。调用 dispose() 的最佳实践是在 FullScreenContentCallback.onAdDismissedFullScreenContent 和 FullScreenContentCallback.onAdFailedToShowFullScreenContent 回调中。
这样就完成了!您的应用现在可以展示插页式广告了。
后续步骤
- 请参阅插页广告最佳实践和插页广告指南。
- 如果还没有,请在Ad Manager 用户界面中创建您自己的插页广告单元。
Ad Manager 原生广告
原生广告是通过平台原生 UI 组件呈现给用户的广告素材。它们使用您已用于构建布局的相同类型的视图展示,并且可以格式化以匹配其所在用户体验的视觉设计。在编码方面,这意味着当原生广告加载时,您的应用会收到一个包含其素材资源的 NativeAd 对象,然后由应用(而不是 Google 移动广告 SDK)负责展示它们。
总的来说,成功实现原生广告有两个方面:通过 SDK 加载广告和展示广告内容。本指南着重于使用 SDK 加载原生广告。
另请参阅 Flutter 中的内嵌广告 Codelab,其中提供了关于设置原生广告的详细指南。
平台设置
原生广告通过平台原生 UI 组件呈现给用户。(例如,Android 上的 View 或 iOS 上的 UIView)。
由于原生广告需要平台原生 UI 组件,因此此功能需要为 Android 和 iOS 进行额外设置。
Android
Google Mobile Ads 插件的 Android 实现需要一个实现 NativeAdFactory 的类。NativeAdFactory 包含一个方法,该方法接收一个 NativeAd 和自定义选项,并返回一个 NativeAdView。NativeAdView 将在您的应用中显示。
您可以在 MainActivity.java 中实现此功能,或在与 MainActivity.java 相同的目录中创建一个单独的类,如下所示。
package my.app.path;
import com.google.android.gms.ads.nativead.NativeAd;
import com.google.android.gms.ads.nativead.NativeAdView;
import io.flutter.plugins.googlemobileads.GoogleMobileAdsPlugin.NativeAdFactory;
import java.util.Map;
class NativeAdFactoryExample implements NativeAdFactory {
@Override
public NativeAdView createNativeAd(
NativeAd nativeAd, Map<String, Object> customOptions) {
// Create NativeAdView
}
}
每个 NativeAdFactory 都需要在 MainActivity.configureFlutterEngine(FlutterEngine) 中使用唯一的 String 标识符 factoryId 进行注册。NativeAdFactory 可以为应用使用的每个唯一的原生广告布局实现和注册,或者一个可以处理所有布局。构建 add-to-app 时,还应在 cleanUpFlutterEngine(engine) 中注销 NativeAdFactory。
MainActivity.java 应如下所示:
package my.app.path;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.googlemobileads.GoogleMobileAdsPlugin;
public class MainActivity extends FlutterActivity {
@Override
public void configureFlutterEngine(FlutterEngine flutterEngine) {
flutterEngine.getPlugins().add(new GoogleMobileAdsPlugin());
super.configureFlutterEngine(flutterEngine);
GoogleMobileAdsPlugin.registerNativeAdFactory(flutterEngine, "adFactoryExample", NativeAdFactoryExample());
}
@Override
public void cleanUpFlutterEngine(FlutterEngine flutterEngine) {
GoogleMobileAdsPlugin.unregisterNativeAdFactory(flutterEngine, "adFactoryExample");
}
}
在 Dart 中创建 NativeAd 时,factoryId 需要与用于将工厂添加到 GoogleMobileAdsPlugin 的 factoryId 匹配。在上面的代码片段中,adFactoryExample 是 factoryId 的名称。下面是一个 NativeAdFactory 示例。
package io.flutter.plugins.googlemobileadsexample;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.widget.TextView;
import com.google.android.gms.ads.nativead.NativeAd;
import com.google.android.gms.ads.nativead.NativeAdView;
import io.flutter.plugins.googlemobileads.GoogleMobileAdsPlugin.NativeAdFactory;
import java.util.Map;
// my_native_ad.xml can be found at
/* https://github.com/googleads/googleads-mobile-flutter/tree/master/packages/google_mobile_ads/example/android/app/src/main/res/layout
*/
class NativeAdFactoryExample implements NativeAdFactory {
private final LayoutInflater layoutInflater;
NativeAdFactoryExample(LayoutInflater layoutInflater) {
this.layoutInflater = layoutInflater;
}
@Override
public NativeAdView createNativeAd(
NativeAd nativeAd, Map<String, Object> customOptions) {
final NativeAdView adView =
(NativeAdView) layoutInflater.inflate(R.layout.my_native_ad, null);
final TextView headlineView = adView.findViewById(R.id.ad_headline);
final TextView bodyView = adView.findViewById(R.id.ad_body);
headlineView.setText(nativeAd.getHeadline());
bodyView.setText(nativeAd.getBody());
adView.setBackgroundColor(Color.YELLOW);
adView.setNativeAd(nativeAd);
adView.setBodyView(bodyView);
adView.setHeadlineView(headlineView);
return adView;
}
}
iOS
Google 移动广告插件的 iOS 实现需要一个实现 FLTNativeAdFactory 的类。FLTNativeAdFactory 包含一个方法,该方法接受一个 GADNativeAd 和自定义选项,并返回一个 GADNativeAdView。GADNativeAdView 将在您的应用中显示。
FLTNativeAdFactory 协议可以由 AppDelegate 实现,或者可以创建一个单独的类,如下所示。
/* AppDelegate.m */
#import "FLTGoogleMobileAdsPlugin.h"
@interface NativeAdFactoryExample : NSObject<FLTNativeAdFactory>
@end
@implementation NativeAdFactoryExample
- (GADNativeAdView *)createNativeAd:(GADNativeAd *)nativeAd
customOptions:(NSDictionary *)customOptions {
// Create GADNativeAdView
}
@end
每个 FLTNativeAdFactory 都需要在 registerNativeAdFactory:factoryId:nativeAdFactory: 中使用唯一的 String 标识符 factoryId 进行注册。FLTNativeAdFactory 可以为应用使用的每个唯一的原生广告布局实现和注册,或者一个可以处理所有布局。这可以通过导入 FLTGoogleMobileAdsPlugin.h 并使用 FlutterPluginRegistry、工厂的唯一标识符以及工厂本身调用 registerNativeAdFactory:factoryId:nativeAdFactory: 来完成。在调用 [GeneratedPluginRegistrant registerWithRegistry:self]; 之后,还必须添加工厂。
如果此操作在 AppDelegate.m 中完成,应如下所示:
#import "FLTGoogleMobileAdsPlugin.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
NativeAdFactoryExample *nativeAdFactory = [[NativeAdFactoryExample alloc] init];
[FLTGoogleMobileAdsPlugin registerNativeAdFactory:self
factoryId:@"adFactoryExample"
nativeAdFactory:nativeAdFactory];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
在 Dart 中创建 NativeAd 时,factoryID 需要与用于将工厂添加到 FLTGoogleMobileAdsPlugin 的 factoryID 匹配。在上面的代码片段中,adFactoryExample 是 factoryID 的名称。下面是一个 FLTNativeAdFactory 示例。
// The example NativeAdView.xib can be found at
/* https://github.com/googleads/googleads-mobile-flutter/blob/master/packages/google_mobile_ads/example/ios/Runner/NativeAdView.xib
*/
@interface NativeAdFactoryExample : NSObject <FLTNativeAdFactory>
@end
@implementation NativeAdFactoryExample
- (GADNativeAdView *)createNativeAd:(GADNativeAd *)nativeAd
customOptions:(NSDictionary *)customOptions {
// Create and place ad in view hierarchy.
GADNativeAdView *adView =
[[NSBundle mainBundle] loadNibNamed:@"NativeAdView" owner:nil options:nil].firstObject;
// Associate the native ad view with the native ad object. This is
// required to make the ad clickable.
adView.nativeAd = nativeAd;
// Populate the native ad view with the native ad assets.
// The headline is guaranteed to be present in every native ad.
((UILabel *)adView.headlineView).text = nativeAd.headline;
// These assets are not guaranteed to be present. Check that they are before
// showing or hiding them.
((UILabel *)adView.bodyView).text = nativeAd.body;
adView.bodyView.hidden = nativeAd.body ? NO : YES;
[((UIButton *)adView.callToActionView) setTitle:nativeAd.callToAction
forState:UIControlStateNormal];
adView.callToActionView.hidden = nativeAd.callToAction ? NO : YES;
((UIImageView *)adView.iconView).image = nativeAd.icon.image;
adView.iconView.hidden = nativeAd.icon ? NO : YES;
((UILabel *)adView.storeView).text = nativeAd.store;
adView.storeView.hidden = nativeAd.store ? NO : YES;
((UILabel *)adView.priceView).text = nativeAd.price;
adView.priceView.hidden = nativeAd.price ? NO : YES;
((UILabel *)adView.advertiserView).text = nativeAd.advertiser;
adView.advertiserView.hidden = nativeAd.advertiser ? NO : YES;
// In order for the SDK to process touch events properly, user interaction
// should be disabled.
adView.callToActionView.userInteractionEnabled = NO;
return adView;
}
@end
始终使用测试广告进行测试
在构建和测试您的应用时,请务必使用测试广告而不是真实、生产中的广告。否则,您的帐号可能会被暂停。
加载原生广告的最简单方法是使用我们专用的原生广告测试广告单元 ID。
- Android:https://developers.google.com/ad-manager/mobile-ads-sdk/android/test-ads#sample_ad_units
- iOS:https://developers.google.com/ad-manager/mobile-ads-sdk/ios/test-ads#demo_ad_units
它经过专门配置,可以为每个请求返回测试广告,您可以在编码、测试和调试时随意在自己的应用中使用它。只需确保在发布应用之前将其替换为您自己的广告单元 ID。
实例化原生广告
NativeAd 需要 adUnitId、factoryId、AdRequest 和 AdListener。下面提供了一个示例,并附有关于每个参数的更多信息。
final NativeAd myNative = NativeAd.fromAdManagerRequest(
adUnitId: '<test id or account id>',
factoryId: 'adFactoryExample',
adManagerRequest: AdManagerAdRequest(),
listener: NativeAdListener(),
);
工厂 ID
factoryId 需要与用于将工厂添加到 Android 上的 GoogleMobileAdsPlugin 和/或 iOS 上的 FLTGoogleMobileAdsPlugin 的 factoryId 匹配。两个平台可以使用相同的 factoryId,或者每个平台都可以有自己的。
原生广告事件
通过使用 NativeAdListener,您可以监听生命周期事件,例如广告关闭或用户离开应用时。此示例实现了每个方法并将消息记录到控制台。
final NativeAdListener listener = NativeAdListener(
// Called when an ad is successfully received.
onAdLoaded: (Ad ad) => print('Ad loaded.'),
// Called when an ad request failed.
onAdFailedToLoad: (Ad ad, LoadAdError error) {
// Dispose the ad here to free resources.
ad.dispose();
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 impression occurs on the ad.
onAdImpression: (Ad ad) => print('Ad impression.'),
// Called when a click is recorded for a NativeAd.
onNativeAdClicked: (NativeAd ad) => print('Ad clicked.'),
);
NativeAdOptions
NativeAds 有一个可选参数 nativeAdOptions,可用于为原生广告设置特定选项。
shouldReturnUrlsForImageAssets
如果设置为 `true`,SDK 将不会加载图片素材内容,并且可以使用原生广告图片 URL 来获取内容。默认为 false。
shouldRequestMultipleImages
某些图片素材资源包含一系列图片,而不仅仅是一张。将此值设置为 true,您的应用即表示已准备好显示任何包含多张图片的素材资源。将其设置为 false(默认值)会指示 SDK 仅提供包含一系列图片的第一个图片素材资源。
如果在初始化 NativeAd 时未传递任何 NativeadOptions,则将使用每个属性的默认值。
adChoicesPlacement
默认情况下,[AdChoices 叠加层](https://developers.google.com/admob/android/native/advanced#adchoices_overlay)设置在右上方。应用可以通过将此属性设置为以下选项之一来更改叠加层渲染的角落:
- AdChoicesPlacement.topLeftCorner
- AdChoicesPlacement.topLeftCorner
- AdChoicesPlacement.bottomRightCorner
- AdChoicesPlacement.bottomLeftCorner
videoOptions
可用于为作为原生广告一部分返回的视频素材资源设置视频选项。
mediaAspectRatio
这会设置要为原生广告返回的图片或视频的纵横比。将 NativeMediaAspectRatio 设置为以下常量之一将仅返回指定纵横比媒体的广告:
- MediaAspectRatio.landscape
- MediaAspectRatio.portrait
- MediaAspectRatio.square
- MediaAspectRatio.any
如果未设置,将返回任何纵横比的广告。
加载原生广告
实例化 NativeAd 后,必须先调用 load() 才能将其显示在屏幕上。
myNative.load();
显示原生广告
要将 NativeAd 显示为小部件,您必须在调用 load() 后实例化一个支持广告的 AdWidget。您可以在调用 load() 之前创建小部件,但必须在将小部件添加到小部件树之前调用 load()。
final AdWidget adWidget = AdWidget(ad: myBanner);
AdWidget 继承自 Flutter 的 Widget 类,可以像任何其他小部件一样使用。在 iOS 上,请确保将小部件放置在一个具有指定宽度和高度的小部件中。否则,您的广告可能不会显示。
final Container adContainer = Container(
alignment: Alignment.center,
child: adWidget,
width: 500,
height: 500,
);
一旦广告调用了 load(),当不再需要访问该广告时,它必须调用 dispose()。调用 dispose() 的最佳实践是在 AdWidget 从小部件树中移除后,或在 AdListener.onAdFailedToLoad 回调中。
这样就完成了!您的应用现在可以展示原生广告了。
后续步骤
Ad Manager 激励广告
激励广告是用户可以选择互动以换取应用内奖励的广告。本指南将向您展示如何将 Ad Manager 的激励广告集成到 Flutter 应用中。
始终使用测试广告进行测试
在构建和测试您的应用时,请务必使用测试广告而不是真实、生产中的广告。否则,您的帐号可能会被暂停。
加载激励广告的最简单方法是使用我们专用的激励广告测试广告单元 ID。
- Android:https://developers.google.com/ad-manager/mobile-ads-sdk/android/test-ads#sample_ad_units
- iOS:https://developers.google.com/ad-manager/mobile-ads-sdk/ios/test-ads#demo_ad_units
它经过专门配置,可以为每个请求返回测试广告,您可以在编码、测试和调试时随意在自己的应用中使用它。只需确保在发布应用之前将其替换为您自己的广告单元 ID。
加载激励广告
加载 RewardedAd 需要 adUnitId、AdManagerAdRequest 和 RewardedAdLoadCallback。下面提供了一个示例,并附有关于每个参数的更多信息。
RewardedAd.loadWithAdManagerAdRequest(
adUnitId: '<test id or account id>',
adManagerRequest: AdManagerAdRequest(),
rewardedAdLoadCallback: RewardedAdLoadCallback(
onAdLoaded: (RewardedAd ad) {
print('$ad loaded.');
// Keep a reference to the ad so you can show it later.
this._rewardedAd = ad;
},
onAdFailedToLoad: (LoadAdError error) {
print('RewardedAd failed to load: $error');
},
);
激励广告事件
通过使用 FullScreenContentCallback,您可以监听生命周期事件,例如广告显示或关闭时。
在展示广告之前设置 RewardedAd.fullScreenContentCallback 以接收这些事件的通知。此示例实现了每个方法并将消息记录到控制台。
rewardedAd.fullScreenContentCallback = FullScreenContentCallback(
onAdShowedFullScreenContent: (RewardedAd ad) =>
print('$ad onAdShowedFullScreenContent.'),
onAdDismissedFullScreenContent: (RewardedAd ad) {
print('$ad onAdDismissedFullScreenContent.');
ad.dispose();
},
onAdFailedToShowFullScreenContent: (RewardedAd ad, AdError error) {
print('$ad onAdFailedToShowFullScreenContent: $error');
ad.dispose();
},
onAdImpression: (RewardedAd ad) => print('$ad impression occurred.'),
);
显示激励广告
RewardedAd 显示为覆盖在所有应用内容之上的叠加层,并且是静态放置的。这意味着它不能以这种方式添加到 Flutter 小部件树中。您可以通过调用 show() 来选择何时展示广告。RewardedAd 只能展示一次。后续的 show 调用将触发 onAdFailedToShowFullScreenContent。
RewardedAd.show() 接受一个 OnUserEarnedRewardCallback,当用户获得奖励时会调用该回调。请务必实现此功能并奖励用户观看广告。
myRewarded.show(onUserEarnedReward: (RewardedAd ad, RewardItem rewardItem) {
// Reward the user for watching an ad.
});
调用 show() 后,以这种方式展示的 Ad 无法以编程方式移除,并且需要用户输入。请勿为已加载的 RewardedAd 调用 show() 多次。而是应加载新广告。
一旦广告调用了 load(),当不再需要访问该广告时,它必须调用 dispose()。调用 dispose() 的最佳实践是在 FullScreenContentCallback.onAdDismissedFullScreenContent 和 FullScreenContentCallback.onAdFailedToShowFullScreenContent 回调中。
这样就完成了!您的应用现在可以展示激励广告了。
后续步骤
- 请参阅激励广告政策。
定位
RequestConfiguration 对象用于收集每次广告请求的全局配置,并通过 MobileAds.instance.updateRequestConfiguration() 应用。
儿童导向设置
根据《儿童在线隐私保护法》(COPPA) 的规定,有一个名为“标记为儿童导向处理”的设置。
作为应用开发者,您可以在发出广告请求时,指明您希望 Google 将您的内容视为儿童导向。如果您指明希望 Google 将您的内容视为儿童导向,我们将采取措施在该广告请求中禁用 IBA 和再营销广告。此设置可通过 RequestConfiguration.tagForChildDirectedTreatment() 与 Google Play 服务 SDK 的所有版本配合使用。
- 使用
TagForChildDirectedTreatment.yes参数,表示您希望根据 COPPA 的规定将您的内容视为儿童导向。 - 使用
TagForChildDirectedTreatment.no参数,表示您不希望根据 COPPA 的规定将您的内容视为儿童导向。 - 如果不想指明您希望如何处理 COPPA 相关的广告请求内容,请使用
TagForChildDirectedTreatment.unspecified参数,或不设置此标记。
以下示例表明,您希望根据 COPPA 的规定将您的内容视为儿童导向
final RequestConfiguration requestConfiguration = RequestConfiguration(
tagForChildDirectedTreatment: TagForChildDirectedTreatment.yes);
MobileAds.instance.updateRequestConfiguration(requestConfiguration);
未达到同意年龄的用户
您可以标记您的广告请求,以便为欧洲经济区 (EEA) 中未达到同意年龄的用户提供相应处理。此功能旨在帮助遵守《通用数据保护条例》(GDPR)。请注意,您可能在 GDPR 下负有其他法律义务。请仔细阅读欧盟的指南并咨询您自己的法律顾问。请记住,Google 的工具旨在帮助遵守规定,但不能免除任何发布商在法律下的义务。详细了解 GDPR 如何影响发布商。
在使用此功能时,会在广告请求中包含一个针对欧洲未达同意年龄用户的标记 (TFUA) 参数。此参数将禁用该特定广告请求的个性化广告(包括再营销)。它还会禁用向第三方广告供应商(如广告衡量像素和第三方广告服务器)的请求。
此设置可通过 RequestConfiguration.tagForUnderAgeOfConsent() 使用。
- 使用
TagForUnderAgeOfConsent.yes参数,表示您希望以适合未达到同意年龄用户的方式处理请求配置。 - 使用
TagForUnderAgeOfConsent.no参数,表示您不希望以适合未达到同意年龄用户的方式处理请求配置。 - 如果不想指明广告请求是否应为欧洲经济区 (EEA) 中未达到同意年龄的用户提供处理,请使用
TagForUnderAgeOfConsent.unspecified参数,或不设置此标记。以下示例表明,您希望在广告请求中包含 TFUA。
final RequestConfiguration requestConfiguration = RequestConfiguration(
tagForUnderAgeOfConsent: TagForUnderAgeOfConsent.yes);
MobileAds.instance.updateRequestConfiguration(requestConfiguration);
启用儿童导向设置的标记和 setTagForUnderAgeOfConsent 不应同时设置为 true。如果同时设置为 true,儿童导向设置将优先。
广告内容过滤
此设置可通过 RequestConfiguration.maxAdContentRating() 设置。
针对这些请求返回的 AdMob 广告的内容级别将在此级别或以下。此网络附加信息的可能值基于数字内容标签分类,并且应为以下 MaxAdContentRating 对象之一:
MaxAdContentRating.gMaxAdContentRating.pgMaxAdContentRating.tMaxAdContentRating.ma
以下代码配置了一个 RequestConfiguration 对象,用于指定返回的广告内容应对应于数字内容标签不超过 G 的级别。
final RequestConfiguration requestConfiguration = RequestConfiguration(
maxAdContentRating: MaxAdContentRating.g);
MobileAds.instance.updateRequestConfiguration(requestConfiguration);
Response Info
为了进行调试和日志记录,LoadAdError 和成功加载的广告
会提供一个 ResponseInfo 对象。此对象包含有关广告的信息
它加载。每个广告格式类都有一个 Ad.responseInfo 属性,该属性
在加载后填充。
ResponseInfo 对象上的属性包括:
mediationAdapterClassName
: 获取当前广告的广告网络的类名。
responseId
: 响应标识符是广告响应的唯一标识符。此
标识符可用于在广告审核中心 (ARC) 中识别和屏蔽广告。
(ARC)。
adapterResponses
: 包含广告响应中每个适配器的元数据的 AdapterResponseInfo 列表。可用于调试中介瀑布流
执行。
execution。
对于瀑布流中的每个广告网络,AdapterResponseInfo 提供以下信息:
属性
| 属性 | 描述 |
|---|---|
| adapterClassName | 标识广告网络的类名。 |
| credentials | 在 AdMob 或 Ad Manager 用户界面中指定的适配器凭证的字符串描述。 |
| adError | 与网络请求相关的错误。如果网络成功加载了广告或网络未被尝试,则为 Null。 |
| latencyMillis | 广告网络加载广告所花费的时间。如果网络未被尝试,则为 0。 |
| 描述 | AdapterResponseInfo 的友好日志字符串版本。 |
广告加载错误
当广告加载失败时,会调用一个失败回调,该回调提供一个
LoadAdError 对象。
以下代码片段检索激励广告加载失败时的错误信息
加载。
onAdFailedToLoad: (ad, loadAdError) {
// Gets the domain from which the error came.
String domain = loadAdError.domain;
// Gets the error code. See
// https://developers.google.com/android/reference/com/google/android/gms/ads/AdRequest
// and https://developers.google.com/admob/ios/api/reference/Enums/GADErrorCode
// for a list of possible codes.
int code = loadAdError.code;
// A log friendly string summarizing the error.
String message = loadAdError.message;
// Get response information, which may include results of mediation requests.
ResponseInfo? responseInfo = loadAdError.responseInfo;
}