Flutter广告集成插件apsl_ads_flutter的使用
Flutter广告集成插件apsl_ads_flutter的使用
1. 简介
Apsl Ads Flutter
是一个用于在Flutter应用程序中无缝集成多个广告网络的插件。通过该插件,您可以轻松地将Google Mobile Ads、Facebook Audience Network和Unity Ads等广告网络集成到您的应用中,从而实现应用的变现。
2. 功能特性
-
Google Mobile Ads:
- Banner(横幅广告)
- AppOpen(应用打开广告)
- Interstitial(插页广告)
- Rewarded Ad(激励视频广告)
- Native Ad(原生广告)
-
Facebook Audience Network:
- Banner(横幅广告)
- Interstitial(插页广告)
- Rewarded Ad(激励视频广告)
- Native Ad(原生广告,即将推出)
-
Unity Ads:
- Banner(横幅广告)
- Interstitial(插页广告)
- Rewarded Ad(激励视频广告)
3. 平台特定设置
iOS平台设置
-
更新Info.plist文件: 在
ios/Runner/Info.plist
中添加以下键值对,以配置Google Ads:<key>GADApplicationIdentifier</key> <string>YOUR_SDK_KEY</string>
同时,添加
SKAdNetworkItems
以支持所有广告网络。您可以参考示例项目的Info.plist来获取完整的SKAdNetworkItems
配置。
Android平台设置
-
更新AndroidManifest.xml文件: 在
android/app/src/main/AndroidManifest.xml
中添加以下元数据,以配置Google Ads:<manifest> <application> <meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/> </application> </manifest>
4. 初始化广告ID
您可以通过继承AdsIdManager
类来定义和管理不同广告网络的广告ID。以下是一个示例:
import 'dart:io';
import 'ads_id_manager.dart';
class TestAdsIdManager extends AdsIdManager {
const TestAdsIdManager();
[@override](/user/override)
List<AppAdIds> get appAdIds => [
AppAdIds(
adNetwork: 'admob',
appId: Platform.isAndroid
? 'ca-app-pub-3940256099942544~3347511713'
: 'ca-app-pub-3940256099942544~1458002511',
appOpenId: Platform.isAndroid
? 'ca-app-pub-3940256099942544/3419835294'
: 'ca-app-pub-3940256099942544/5662855259',
bannerId: Platform.isAndroid
? 'ca-app-pub-3940256099942544/6300978111'
: 'ca-app-pub-3940256099942544/2934735716',
interstitialId: Platform.isAndroid
? 'ca-app-pub-3940256099942544/1033173712'
: 'ca-app-pub-3940256099942544/4411468910',
rewardedId: Platform.isAndroid
? 'ca-app-pub-3940256099942544/5224354917'
: 'ca-app-pub-3940256099942544/1712485313',
nativeId: Platform.isAndroid
? 'ca-app-pub-3940256099942544/2247696110'
: 'ca-app-pub-3940256099942544/3986624511',
),
AppAdIds(
adNetwork: 'unity',
appId: Platform.isAndroid ? '4374881' : '4374880',
bannerId: Platform.isAndroid ? 'Banner_Android' : 'Banner_iOS',
interstitialId:
Platform.isAndroid ? 'Interstitial_Android' : 'Interstitial_iOS',
rewardedId: Platform.isAndroid ? 'Rewarded_Android' : 'Rewarded_iOS',
),
const AppAdIds(
adNetwork: 'facebook',
appId: '1579706379118402',
interstitialId: 'VID_HD_16_9_15S_LINK#YOUR_PLACEMENT_ID',
bannerId: 'IMG_16_9_APP_INSTALL#YOUR_PLACEMENT_ID',
rewardedId: 'VID_HD_16_9_46S_APP_INSTALL#YOUR_PLACEMENT_ID',
),
];
}
5. SDK初始化
在显示广告之前,必须先初始化Mobile Ads SDK。建议在应用启动时进行初始化。以下是初始化的代码示例:
import 'package:apsl_ads_flutter/apsl_ads_flutter.dart';
import 'package:flutter/material.dart';
const IAdIdManager adIdManager = TestAdsIdManager();
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await ApslAds.instance.initialize(
isShowAppOpenOnAppStateChange: true,
adIdManager,
unityTestMode: true,
fbTestMode: true,
fbTestingId: "334B90C731BDB120067DE02818259A5A",
adMobAdRequest: const AdRequest(),
admobConfiguration: RequestConfiguration(
testDeviceIds: ["334B90C731BDB120067DE02818259A5A"]),
showAdBadge: false,
fbiOSAdvertiserTrackingEnabled: true,
preloadRewardedAds: false,
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Apsl Ads Example',
home: HomeScreen(),
);
}
}
6. 显示广告
插页广告(Interstitial Ad)
-
加载插页广告: 您可以使用
ApslAds.instance.loadAd()
方法来加载插页广告。ApslAds.instance.loadAd();
-
显示插页广告: 使用
ApslAds.instance.showAd(AdUnitType.interstitial)
方法来显示插页广告。ApslAds.instance.showAd(AdUnitType.interstitial);
激励视频广告(Rewarded Ad)
-
加载并显示激励视频广告: 使用
ApslAds.instance.loadAndShowRewardedAd()
方法来加载并显示激励视频广告。ApslAds.instance.loadAndShowRewardedAd( context: context, adNetwork: AdNetwork.admob, );
应用打开广告(App Open Ad)
-
显示应用打开广告: 使用
ApslAds.instance.showAd(AdUnitType.appOpen)
方法来显示应用打开广告。ApslAds.instance.showAd(AdUnitType.appOpen);
横幅广告(Banner Ad)
-
在Widget树中显示横幅广告: 您可以在Widget树中的任意位置插入
ApslBannerAd
来显示横幅广告。[@override](/user/override) Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ SomeWidget(), const Spacer(), ApslBannerAd( adNetwork: AdNetwork.admob, adSize: AdSize.mediumRectangle, ), ], ); }
-
按顺序显示多个横幅广告: 使用
ApslAllBannerAd
可以按顺序尝试从不同的广告网络加载横幅广告。如果一个网络失败,它会自动切换到下一个网络。[@override](/user/override) Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('My App'), ), body: Column( children: [ // 其他Widget... ApslAllBannerAd( orderOfAdNetworks: [ AdNetwork.facebook, AdNetwork.admob, AdNetwork.unity, ], adSize: AdSize.largeBanner, ), // 其他Widget... ], ), ); }
7. 回调机制
为了监听广告事件,您可以使用回调机制。以下是一个监听插页广告关闭事件的示例:
StreamSubscription? _streamSubscription;
if (ApslAds.instance.showInterstitialAd()) {
// 取消上次订阅的回调
_streamSubscription?.cancel();
// 监听插页广告关闭事件
_streamSubscription = ApslAds.instance.onEvent.listen((event) {
if (event.adUnitType == AdUnitType.interstitial && event.type == AdEventType.adDismissed) {
_streamSubscription?.cancel();
goToNextScreen(countryList[index]);
}
});
}
8. 完整示例Demo
以下是一个完整的示例应用,展示了如何集成和显示不同类型的广告:
import 'dart:async';
import 'package:apsl_ads_flutter/apsl_ads_flutter.dart';
import 'package:flutter/material.dart';
const AdsIdManager adIdManager = TestAdsIdManager();
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await ApslAds.instance.initialize(
isShowAppOpenOnAppStateChange: true,
adIdManager,
unityTestMode: true,
fbTestMode: true,
fbTestingId: "334B90C731BDB120067DE02818259A5A",
adMobAdRequest: const AdRequest(),
admobConfiguration: RequestConfiguration(
testDeviceIds: ["334B90C731BDB120067DE02818259A5A"]),
showAdBadge: false,
fbiOSAdvertiserTrackingEnabled: true,
preloadRewardedAds: false,
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
[@override](/user/override)
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Apsl Ads Example',
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
[@override](/user/override)
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
StreamSubscription? _streamSubscription;
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("List of Ads"),
centerTitle: true,
),
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
_sectionTitleWidget(context, title: 'App Open'),
AdListTile(
networkName: 'Admob AppOpen',
onTap: () => _showAd(AdUnitType.appOpen, adNetwork: AdNetwork.admob),
),
const ApslSequenceNativeAd(
templateType: TemplateType.small,
),
const Divider(thickness: 2),
_sectionTitleWidget(context, title: 'Interstitial'),
AdListTile(
networkName: 'Admob Interstitial',
onTap: () => _showAd(AdUnitType.interstitial, adNetwork: AdNetwork.admob),
),
AdListTile(
networkName: 'Facebook Interstitial',
onTap: () => _showAd(AdUnitType.interstitial, adNetwork: AdNetwork.facebook),
),
AdListTile(
networkName: 'Unity Interstitial',
onTap: () => _showAd(AdUnitType.interstitial, adNetwork: AdNetwork.unity),
),
AdListTile(
networkName: 'Show Interstitial one by one',
onTap: () => _showAd(AdUnitType.interstitial),
),
AdListTile(
networkName: 'Show on Navigation',
onTap: () => _showAd(AdUnitType.interstitial, navigate: true),
),
const Divider(thickness: 2),
_sectionTitleWidget(context, title: 'Rewarded'),
AdListTile(
networkName: 'Admob Rewarded',
onTap: () => _loadAndShowRewardedAds(adNetwork: AdNetwork.admob),
),
AdListTile(
networkName: 'Facebook Rewarded',
onTap: () => _loadAndShowRewardedAds(adNetwork: AdNetwork.facebook),
),
AdListTile(
networkName: 'Unity Rewarded',
onTap: () => _loadAndShowRewardedAds(adNetwork: AdNetwork.unity),
),
AdListTile(
networkName: 'Show Rewarded one by one',
onTap: () => _loadAndShowRewardedAds(adNetwork: AdNetwork.any),
),
const ApslSequenceBannerAd(
orderOfAdNetworks: [
AdNetwork.admob,
AdNetwork.unity,
AdNetwork.facebook,
],
),
],
),
),
),
);
}
Widget _sectionTitleWidget(BuildContext context, {String title = ""}) {
return ListTile(
title: Text(
title,
style: Theme.of(context)
.textTheme
.headlineSmall!
.copyWith(color: Colors.blue, fontWeight: FontWeight.bold),
),
);
}
void _showAd(
AdUnitType adUnitType, {
AdNetwork adNetwork = AdNetwork.any,
bool navigate = false,
}) {
if (ApslAds.instance.showAd(adUnitType, adNetwork: adNetwork)) {
if (navigate) {
_streamSubscription?.cancel();
_streamSubscription = ApslAds.instance.onEvent.listen((event) {
if (event.adUnitType == adUnitType) {
_streamSubscription?.cancel();
_goToNextScreen(adNetwork: adNetwork);
}
});
}
} else {
if (navigate) _goToNextScreen(adNetwork: adNetwork);
}
}
void _loadAndShowRewardedAds({required AdNetwork adNetwork}) {
ApslAds.instance.loadAndShowRewardedAd(
context: context,
adNetwork: adNetwork,
);
_streamSubscription?.cancel();
_streamSubscription = ApslAds.instance.onEvent.listen((event) {
if (event.adUnitType == AdUnitType.rewarded) {
if (event.type == AdEventType.adDismissed) {
} else if (event.type == AdEventType.adFailedToShow) {
_showCustomDialog(
context,
title: "Ads not available",
description: "Please try again later.",
);
} else if (event.type == AdEventType.earnedReward) {
_showCustomDialog(
context,
title: "Congratulations",
description: "You earned rewards",
);
}
}
});
}
void _goToNextScreen({AdNetwork? adNetwork}) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(adNetwork: adNetwork),
),
);
}
void _showCustomDialog(BuildContext context,
{required String title, required String description}) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(title),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text(description),
],
),
),
actions: <Widget>[
TextButton(
child: const Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
class DetailScreen extends StatefulWidget {
final AdNetwork? adNetwork;
const DetailScreen({super.key, this.adNetwork = AdNetwork.admob});
[@override](/user/override)
State<DetailScreen> createState() => _DetailScreenState();
}
class _DetailScreenState extends State<DetailScreen> {
late final WebViewController _webViewController;
[@override](/user/override)
void initState() {
super.initState();
_webViewController = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(const Color(0x00000000))
..setNavigationDelegate(
NavigationDelegate(
onProgress: (int progress) {
// 更新加载进度条
},
onPageStarted: (String url) {},
onPageFinished: (String url) {},
onWebResourceError: (WebResourceError error) {},
onNavigationRequest: (NavigationRequest request) {
if (request.url.startsWith('https://www.youtube.com/')) {
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
),
)
..loadRequest(Uri.parse(
"https://support.google.com/admob/answer/9234653?hl=en#:~:text=AdMob%20is%20a%20mobile%20ad,helping%20you%20serve%20ads%20globally."));
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("ApslAds Example")),
body: WebViewWidget(
controller: _webViewController,
),
);
}
}
class AdListTile extends StatelessWidget {
final String networkName;
final VoidCallback onTap;
const AdListTile({super.key, required this.networkName, required this.onTap});
[@override](/user/override)
Widget build(BuildContext context) {
return ListTile(
title: Text(
networkName,
style: const TextStyle(
fontSize: 22,
fontWeight: FontWeight.w400,
color: Colors.black54,
),
),
trailing: const Icon(Icons.arrow_forward_ios),
onTap: onTap,
);
}
}
更多关于Flutter广告集成插件apsl_ads_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter广告集成插件apsl_ads_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter项目中集成广告功能可以通过使用各种广告网络提供的插件来实现。apsl_ads_flutter
是一个用于集成广告的 Flutter 插件,它支持多种广告格式,如横幅广告(Banner Ads)、插页式广告(Interstitial Ads)和视频广告(Video Ads)。
以下是如何在 Flutter 项目中使用 apsl_ads_flutter
插件的一个基本示例。
1. 添加依赖
首先,在你的 Flutter 项目的 pubspec.yaml
文件中添加 apsl_ads_flutter
依赖:
dependencies:
flutter:
sdk: flutter
apsl_ads_flutter: ^最新版本号 # 请替换为实际的最新版本号
然后,运行 flutter pub get
来获取依赖。
2. 配置广告网络
apsl_ads_flutter
支持多种广告网络,例如 Google AdMob、Facebook Audience Network 等。你需要在相应的广告网络平台上注册你的应用,并获取广告单元 ID(Ad Unit ID)。
3. 初始化插件
在你的 Flutter 应用的入口文件(通常是 main.dart
)中,初始化 ApslAds
插件。
import 'package:flutter/material.dart';
import 'package:apsl_ads_flutter/apsl_ads_flutter.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// 初始化广告插件
ApslAds.init(
adsConfig: AdsConfig(
// 替换为你的广告网络配置
admobAppId: '你的AdMob应用ID',
facebookAppId: '你的Facebook应用ID', // 可选
),
);
return MaterialApp(
home: HomeScreen(),
);
}
}
4. 显示横幅广告
在你的应用中显示横幅广告,例如在 HomeScreen
中:
import 'package:flutter/material.dart';
import 'package:apsl_ads_flutter/apsl_ads_flutter.dart';
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
BannerAd? _bannerAd;
@override
void initState() {
super.initState();
// 创建横幅广告实例
_bannerAd = BannerAd(
adUnitId: '你的横幅广告单元ID',
adSize: AdSize.banner,
listener: BannerAdListener(
onAdLoaded: () {
print('Banner Ad Loaded');
},
onAdFailedToLoad: (error) {
print('Banner Ad Failed to Load: $error');
},
onAdOpened: () {
print('Banner Ad Opened');
},
onAdClosed: () {
print('Banner Ad Closed');
},
onAdLeftApplication: () {
print('Banner Ad Left Application');
},
),
);
// 加载横幅广告
_bannerAd?.load();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('广告集成示例'),
),
body: Column(
children: [
// 显示横幅广告
if (_bannerAd?.isLoaded ?? false)
AdWidget(ad: _bannerAd!),
// 其他内容
Center(
child: Text('这里是其他内容'),
),
],
),
);
}
@override
void dispose() {
// 释放横幅广告资源
_bannerAd?.dispose();
super.dispose();
}
}
5. 显示插页式广告
类似地,你可以显示插页式广告:
import 'package:apsl_ads_flutter/apsl_ads_flutter.dart';
// 假设在某个按钮点击事件中显示插页式广告
void _showInterstitialAd() {
InterstitialAd.load(
adUnitId: '你的插页式广告单元ID',
listener: InterstitialAdListener(
onAdLoaded: () {
InterstitialAd.show();
},
onAdFailedToLoad: (error) {
print('Interstitial Ad Failed to Load: $error');
},
onAdOpened: () {
print('Interstitial Ad Opened');
},
onAdClosed: () {
print('Interstitial Ad Closed');
},
),
);
}
总结
以上代码展示了如何在 Flutter 项目中使用 apsl_ads_flutter
插件来集成和显示横幅广告和插页式广告。根据你的需求,你可以进一步集成视频广告等其他广告格式,并处理更多的广告事件。请确保在实际应用中处理广告加载失败和广告刷新等逻辑,以提供良好的用户体验。