applovin_ads_controller.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. // Copyright 2022, the Flutter project authors. Please see the AUTHORS file
  2. // for details. All rights reserved. Use of this source code is governed by a
  3. // BSD-style license that can be found in the LICENSE file.
  4. import 'dart:async';
  5. import 'dart:math';
  6. import 'package:applovin_max/applovin_max.dart';
  7. import 'package:flutter/foundation.dart';
  8. import 'package:flutter/material.dart';
  9. import 'package:flutter/services.dart';
  10. import 'package:logging/logging.dart';
  11. import 'package:puzzleweave/ads/ad_helper.dart';
  12. import 'package:puzzleweave/firebase/adjust_helper.dart';
  13. import 'package:puzzleweave/firebase/firebase_helper.dart';
  14. import '../persistence/persistence.dart';
  15. import '../remote_config/remote_config.dart';
  16. import '../statistics/statistics.dart';
  17. final Logger _log = Logger('ApplovinAdsController');
  18. const int bannerReportDuration = 3 * 60 * 1000; // banner paid 3分钟报一次
  19. /// Allows showing ads. A facade for `package:google_mobile_ads`.
  20. class ApplovinAdsController {
  21. final BuildContext context;
  22. late double bannerPaidValueMicros; // banner广告累计收益
  23. late int lastBannerPaidReportTimestamp; // 上次banner广告收益上报时间戳,用于控制banner广告收益上报频率
  24. late double allPaidValueMicros; // 所有广告累计收益
  25. late double revenueThreshold; // 广告累计上报阈值
  26. bool _hasInit = false;
  27. bool get hasInit => _hasInit;
  28. final Completer<bool> completer = Completer();
  29. /// Creates an [ApplovinAdsController] that wraps around a [MobileAds] [instance].
  30. ///
  31. /// Example usage:
  32. ///
  33. /// var controller = ApplovinAdsController(MobileAds.instance);
  34. ApplovinAdsController(this.context);
  35. void dispose() {}
  36. /// Initializes the injected [MobileAds.instance].
  37. Future<void> initialize() async {
  38. if (_hasInit) return;
  39. _log.info('AppLovinMAX.initialize...');
  40. // 用于模拟测试欧洲UMP是否正常,release版本注意注释掉
  41. // AppLovinMAX.setVerboseLogging(true);
  42. // AppLovinMAX.setConsentFlowDebugUserGeography(ConsentFlowUserGeography.gdpr);
  43. // 1. 开启合规流开关
  44. AppLovinMAX.setTermsAndPrivacyPolicyFlowEnabled(true);
  45. // 2. 设置你的隐私政策和用户协议链接(必须是有效的 URL)
  46. AppLovinMAX.setPrivacyPolicyUrl("https://longreachai.net/game/privacy_policy.html");
  47. AppLovinMAX.setTermsOfServiceUrl("https://longreachai.net/game/terms_of_service.html");
  48. // 3. 然后再初始化 SDK
  49. MaxConfiguration? sdkConfiguration = await AppLovinMAX.initialize(AdHelper.applovinSdkKey);
  50. _log.info('AppLovinMAX.initialize success!');
  51. lastBannerPaidReportTimestamp = Persistence().lastBannerPaidReportTimestamp;
  52. bannerPaidValueMicros = Persistence().bannerPaidValueMicros;
  53. allPaidValueMicros = Persistence().allPaidValueMicros;
  54. revenueThreshold = RemoteConfig().adRevenueThreshold;
  55. if (revenueThreshold <= 0.0) revenueThreshold = 0.01;
  56. initializeBannerAds();
  57. initializeInterstitialAds();
  58. initializeRewardedAd();
  59. completer.complete(true);
  60. _hasInit = true;
  61. }
  62. void initializeBannerAds() {
  63. AppLovinMAX.setBannerExtraParameter(AdHelper.applovinBannerAdUnitId, "adaptive_banner", "true");
  64. // MAX automatically sizes banners to 320×50 on phones and 728×90 on tablets
  65. // 移除这一行,避免与 MaxAdView Widget 冲突!
  66. // AppLovin MAX 在 Flutter 中的最佳实践是只使用 MaxAdView Widget,让 Flutter 来管理 Banner 视图的布局和生命周期
  67. // 同时调用 AppLovinMAX.createBanner (原生创建) 和渲染 MaxAdView (Flutter Widget),特别是在 iOS 上,原生层可能会意外地创建了一个透明的全屏视图来管理广告
  68. // AppLovinMAX.createBanner(AdHelper.applovinBannerAdUnitId, AdViewPosition.bottomCenter);
  69. }
  70. Widget getBannerWidget(String positionKey) {
  71. // 如果调用时 SDK 还没初始化完成,返回空,避免 Native 层空指针
  72. if (!_hasInit) return const SizedBox.shrink();
  73. return MaxAdView(
  74. key: ValueKey(positionKey), // 只要 positionKey 不变,页面内刷新就不会重建
  75. adUnitId: AdHelper.applovinBannerAdUnitId,
  76. adFormat: AdFormat.banner,
  77. placement: 'banner',
  78. extraParameters: const {'adaptive_banner': 'true'},
  79. listener: AdViewAdListener(
  80. onAdLoadedCallback: (ad) {
  81. // // 广告加载成功后, ad.size 包含实际的宽度和高度 (dp)
  82. // double? widthDp = ad.size?.width;
  83. // double? heightDp = ad.size?.height;
  84. // if (heightDp != null) {
  85. // context.read<Device>().bannerHeight = heightDp;
  86. // }
  87. // _log.info('banner广告 width = $widthDp, height = $heightDp');
  88. _log.info(() => 'applovin banner Ad loaded: ${ad.hashCode}');
  89. },
  90. onAdLoadFailedCallback: (adUnitId, error) {
  91. _log.warning('applovin banner Ad failedToLoad: $error');
  92. },
  93. onAdClickedCallback: (ad) {
  94. _log.info('applovin banner Ad click registered');
  95. },
  96. onAdExpandedCallback: (ad) {
  97. _log.info('applovin banner Ad expanded');
  98. },
  99. onAdCollapsedCallback: (ad) {
  100. _log.info('applovin banner Ad collaspsed');
  101. },
  102. onAdRevenuePaidCallback: (ad) {
  103. _log.info('woooooooooo, applovin banner paid event: revenue: ${ad.revenue} precision: ${ad.revenuePrecision}');
  104. if (ad.revenue > 0) {
  105. onAdRevenuePaid(ad); // revenue 单位转化为 valueMicro,以便和admod一致
  106. }
  107. },
  108. ),
  109. );
  110. }
  111. // revenue 回调处理,所有广告类型统一在此处理
  112. onAdRevenuePaid(MaxAd ad) async {
  113. _log.info('report ad revenue paid: ${ad.revenue}');
  114. Map<String, Object> params = {
  115. "ad_platform": 'appLovin',
  116. "ad_source": ad.networkName,
  117. "ad_format": ad.placement,
  118. "ad_unit_name": ad.adUnitId,
  119. "value": ad.revenue,
  120. "currency": "USD",
  121. };
  122. // for ARO : ad_impression 上报给firebase
  123. FirebaseHelper.logEvent("ad_impression", params);
  124. // for Taichi
  125. FirebaseHelper.logEvent("Ad_Impression_Revenue", params);
  126. // 累计超过0.01 USD 上报 Total_Ads_Revenue_001
  127. double previousTroasCache = Persistence().tRoasCache;
  128. double currentTroasCache = previousTroasCache + ad.revenue;
  129. if (currentTroasCache >= revenueThreshold) {
  130. FirebaseHelper.logEvent("Total_Ads_Revenue_001", {"value": currentTroasCache, "currency": "USD"});
  131. Persistence().tRoasCache = 0; // 缓存清零
  132. } else {
  133. Persistence().tRoasCache = currentTroasCache;
  134. }
  135. // adRevenue 事件上报给adjust
  136. AdjustHelper.trackAdRevenue(ad.placement, 1, ad.revenue, 'USD');
  137. // revenue 埋点时间上报给自主BI平台
  138. Statistics.postEvent({
  139. "project_id": Persistence().projectId,
  140. "user_id": Persistence().uuid,
  141. "library_name": Persistence().libraryName,
  142. "library_version": Persistence().packageVersion,
  143. "name": 'revenue',
  144. "tab_source": adSrc,
  145. "sku_id": skuId,
  146. "ad_src": adSrc,
  147. "ad_type": ad.placement,
  148. "ad_rev": ad.revenue,
  149. });
  150. }
  151. //////////////////////////// interstitialAd /////////////////////////////
  152. final int _maxExponentialRetryCount = 6;
  153. var _interstitialRetryAttempt = 0;
  154. ValueNotifier<AdState> interstitialAdState = ValueNotifier(AdState.initial);
  155. void initializeInterstitialAds() {
  156. AppLovinMAX.setInterstitialListener(
  157. InterstitialListener(
  158. onAdLoadedCallback: (ad) {
  159. // Interstitial ad is ready to show. AppLovinMAX.isInterstitialReady(_interstitial_ad_unit_ID) now returns 'true'.
  160. _log.info('Interstitial ad loaded from ${ad.networkName}');
  161. // Reset retry attempt
  162. _interstitialRetryAttempt = 0;
  163. interstitialAdState.value = AdState.ready;
  164. },
  165. onAdLoadFailedCallback: (adUnitId, error) {
  166. // Interstitial ad failed to load.
  167. // AppLovin recommends that you retry with exponentially higher delays up to a maximum delay (in this case 64 seconds).
  168. _interstitialRetryAttempt = _interstitialRetryAttempt + 1;
  169. if (_interstitialRetryAttempt > _maxExponentialRetryCount) return;
  170. int retryDelay = pow(2, min(_maxExponentialRetryCount, _interstitialRetryAttempt)).toInt();
  171. if (kDebugMode) {
  172. _log.info('Interstitial ad failed to load with code ${error.code} - retrying in ${retryDelay}s');
  173. }
  174. Future.delayed(Duration(milliseconds: retryDelay * 1000), () {
  175. AppLovinMAX.loadInterstitial(AdHelper.applovinInterstitialAdUnitId);
  176. });
  177. },
  178. onAdDisplayedCallback: (ad) {
  179. _log.info('interstitialAd displayed');
  180. interstitialAdState.value = AdState.showing; // 广告成功展示
  181. },
  182. onAdDisplayFailedCallback: (ad, error) {
  183. _log.info('interstitialAd display failed');
  184. interstitialAdState.value = AdState.error; // 广告显示异常
  185. },
  186. onAdClickedCallback: (ad) {},
  187. onAdHiddenCallback: (ad) {
  188. _log.info('interstitialAd hidden');
  189. interstitialAdState.value = AdState.dismissed; // 广告关闭
  190. AppLovinMAX.loadInterstitial(AdHelper.applovinInterstitialAdUnitId);
  191. },
  192. onAdRevenuePaidCallback: (ad) {
  193. _log.info('woooooooooo, applovin interstitial paid event: revenue: ${ad.revenue}, precision: ${ad.revenuePrecision}');
  194. if (ad.revenue > 0) {
  195. onAdRevenuePaid(ad); // revenue 单位转化为 valueMicro,以便和admod一致
  196. }
  197. },
  198. ),
  199. );
  200. // Load the first interstitial.
  201. Future.delayed(const Duration(seconds: 3), () {
  202. loadInterstitialAd();
  203. });
  204. }
  205. void loadInterstitialAd() async {
  206. if (!_hasInit) return;
  207. bool? isInit = await AppLovinMAX.isInitialized();
  208. if (isInit == null || !isInit) {
  209. return;
  210. }
  211. bool isReady = (await AppLovinMAX.isInterstitialReady(AdHelper.applovinInterstitialAdUnitId))!;
  212. if (isReady) {
  213. _log.info("applovin interstitial ad already ready, no need to load!");
  214. return;
  215. }
  216. AppLovinMAX.loadInterstitial(AdHelper.applovinInterstitialAdUnitId);
  217. }
  218. Future<bool> isInterstitialAdReady() async {
  219. if (!_hasInit) return false;
  220. try {
  221. bool? isInit = await AppLovinMAX.isInitialized();
  222. if (isInit == null || !isInit) {
  223. return false;
  224. }
  225. bool isReady = (await AppLovinMAX.isInterstitialReady(AdHelper.applovinInterstitialAdUnitId))!;
  226. return isReady;
  227. } catch (e) {
  228. _log.warning('isInterstitialReady error: $e');
  229. }
  230. return false;
  231. }
  232. String adSrc = "";
  233. String skuId = "";
  234. showInterstitialAd({String adSrc = "", String skuId = ""}) async {
  235. this.adSrc = adSrc;
  236. this.skuId = skuId;
  237. try {
  238. bool? isInit = await AppLovinMAX.isInitialized();
  239. if (isInit == null || !isInit) {
  240. return;
  241. }
  242. bool isReady = (await AppLovinMAX.isInterstitialReady(AdHelper.applovinInterstitialAdUnitId))!;
  243. if (isReady) {
  244. AppLovinMAX.showInterstitial(AdHelper.applovinInterstitialAdUnitId, placement: 'inters');
  245. } else {
  246. AppLovinMAX.loadInterstitial(AdHelper.applovinInterstitialAdUnitId);
  247. }
  248. } on PlatformException catch (e) {
  249. _log.warning('PlatformException: $e');
  250. } catch (e) {
  251. _log.warning('showInterstitialAd: $e');
  252. }
  253. }
  254. //////////////////////////// rewardedAd /////////////////////////////
  255. ValueNotifier<AdState> rewardedAdState = ValueNotifier(AdState.initial);
  256. var _rewardedAdRetryAttempt = 0;
  257. void initializeRewardedAd() {
  258. AppLovinMAX.setRewardedAdListener(
  259. RewardedAdListener(
  260. onAdLoadedCallback: (ad) {
  261. // Rewarded ad is ready to show. AppLovinMAX.isRewardedAdReady(_rewarded_ad_unit_ID) now returns 'true'.
  262. _log.info('Rewarded ad loaded from ${ad.networkName}');
  263. // Reset retry attempt
  264. _rewardedAdRetryAttempt = 0;
  265. rewardedAdState.value = AdState.ready;
  266. },
  267. onAdLoadFailedCallback: (adUnitId, error) {
  268. // Rewarded ad failed to load.
  269. // AppLovin recommends that you retry with exponentially higher delays up to a maximum delay (in this case 64 seconds).
  270. _rewardedAdRetryAttempt = _rewardedAdRetryAttempt + 1;
  271. if (_rewardedAdRetryAttempt > _maxExponentialRetryCount) return;
  272. int retryDelay = pow(2, min(_maxExponentialRetryCount, _rewardedAdRetryAttempt)).toInt();
  273. _log.info('Rewarded ad failed to load with code ${error.code} - retrying in ${retryDelay}s');
  274. Future.delayed(Duration(milliseconds: retryDelay * 1000), () {
  275. AppLovinMAX.loadRewardedAd(AdHelper.applovinRewardedAdUnitId);
  276. });
  277. },
  278. onAdDisplayedCallback: (ad) {
  279. _log.info('rewardedAd displayed');
  280. rewardedAdState.value = AdState.showing; // 广告成功展示
  281. },
  282. onAdDisplayFailedCallback: (ad, error) {
  283. _log.info('rewardedAd display failed');
  284. rewardedAdState.value = AdState.error; // 广告显示异常
  285. rewardCallback = null;
  286. },
  287. onAdClickedCallback: (ad) {},
  288. onAdHiddenCallback: (ad) {
  289. _log.info('rewardedAd hide');
  290. rewardedAdState.value = AdState.dismissed; // 广告关闭
  291. rewardCallback = null;
  292. AppLovinMAX.loadRewardedAd(AdHelper.applovinRewardedAdUnitId);
  293. },
  294. onAdReceivedRewardCallback: (ad, reward) {
  295. _log.info('rewardedAd receive reward: $reward');
  296. rewardCallback?.call(ad, reward);
  297. },
  298. onAdRevenuePaidCallback: (ad) {
  299. _log.info('woooooooooo, applovin rewarded paid event: revenue: ${ad.revenue} precision: ${ad.revenuePrecision}');
  300. if (ad.revenue > 0) {
  301. onAdRevenuePaid(ad); // revenue 单位转化为 valueMicro,以便和admod一致
  302. }
  303. },
  304. ),
  305. );
  306. // Load the first reward ad.
  307. // loadRewardedAd();
  308. Future.delayed(const Duration(seconds: 3), () {
  309. loadRewardedAd();
  310. });
  311. }
  312. void loadRewardedAd() async {
  313. if (!_hasInit) return;
  314. bool? isInit = await AppLovinMAX.isInitialized();
  315. if (isInit == null || !isInit) {
  316. _log.warning("applovin not initialized yet!");
  317. return;
  318. }
  319. bool isReady = (await AppLovinMAX.isRewardedAdReady(AdHelper.applovinRewardedAdUnitId))!;
  320. if (isReady) {
  321. _log.info("applovin reward ad already ready, no need to load!");
  322. return;
  323. }
  324. AppLovinMAX.loadRewardedAd(AdHelper.applovinRewardedAdUnitId);
  325. }
  326. Future<bool> isRewardedAdReady() async {
  327. if (!_hasInit) return false;
  328. try {
  329. bool? isInit = await AppLovinMAX.isInitialized();
  330. if (isInit == null || !isInit) {
  331. return false;
  332. }
  333. bool isReady = (await AppLovinMAX.isRewardedAdReady(AdHelper.applovinRewardedAdUnitId))!;
  334. return isReady;
  335. } catch (e) {
  336. _log.warning('isInterstitialReady error: $e');
  337. }
  338. return false;
  339. }
  340. Function(MaxAd, MaxReward)? rewardCallback;
  341. Future<bool> showRewardedlAd({required onUserEarnedReward, String adSrc = "", String skuId = ""}) async {
  342. this.adSrc = adSrc;
  343. this.skuId = skuId;
  344. rewardCallback = null;
  345. try {
  346. bool? isInit = await AppLovinMAX.isInitialized();
  347. if (isInit == null || !isInit) {
  348. return false;
  349. }
  350. bool isReady = (await AppLovinMAX.isRewardedAdReady(AdHelper.applovinRewardedAdUnitId))!;
  351. if (isReady) {
  352. AppLovinMAX.showRewardedAd(AdHelper.applovinRewardedAdUnitId, placement: 'reward');
  353. rewardCallback = onUserEarnedReward;
  354. return true;
  355. } else {
  356. AppLovinMAX.loadRewardedAd(AdHelper.applovinRewardedAdUnitId);
  357. return false;
  358. }
  359. } on PlatformException catch (e) {
  360. _log.warning('PlatformException: $e');
  361. return false;
  362. } catch (e) {
  363. _log.warning('showRewardedlAd error: $e');
  364. return false;
  365. }
  366. }
  367. }