applovin_ads_controller.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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 get bannerAdWidget => MaxAdView(
  71. adUnitId: AdHelper.applovinBannerAdUnitId,
  72. adFormat: AdFormat.banner,
  73. placement: 'banner',
  74. extraParameters: const {'adaptive_banner': 'true'},
  75. listener: AdViewAdListener(
  76. onAdLoadedCallback: (ad) {
  77. // // 广告加载成功后, ad.size 包含实际的宽度和高度 (dp)
  78. // double? widthDp = ad.size?.width;
  79. // double? heightDp = ad.size?.height;
  80. // if (heightDp != null) {
  81. // context.read<Device>().bannerHeight = heightDp;
  82. // }
  83. // _log.info('banner广告 width = $widthDp, height = $heightDp');
  84. _log.info(() => 'applovin banner Ad loaded: ${ad.hashCode}');
  85. },
  86. onAdLoadFailedCallback: (adUnitId, error) {
  87. _log.warning('applovin banner Ad failedToLoad: $error');
  88. },
  89. onAdClickedCallback: (ad) {
  90. _log.info('applovin banner Ad click registered');
  91. },
  92. onAdExpandedCallback: (ad) {
  93. _log.info('applovin banner Ad expanded');
  94. },
  95. onAdCollapsedCallback: (ad) {
  96. _log.info('applovin banner Ad collaspsed');
  97. },
  98. onAdRevenuePaidCallback: (ad) {
  99. _log.info('woooooooooo, applovin banner paid event: revenue: ${ad.revenue} precision: ${ad.revenuePrecision}');
  100. if (ad.revenue > 0) {
  101. onAdRevenuePaid(ad); // revenue 单位转化为 valueMicro,以便和admod一致
  102. }
  103. },
  104. ),
  105. );
  106. // revenue 回调处理,所有广告类型统一在此处理
  107. onAdRevenuePaid(MaxAd ad) async {
  108. _log.info('report ad revenue paid: ${ad.revenue}');
  109. Map<String, Object> params = {
  110. "ad_platform": 'appLovin',
  111. "ad_source": ad.networkName,
  112. "ad_format": ad.placement,
  113. "ad_unit_name": ad.adUnitId,
  114. "value": ad.revenue,
  115. "currency": "USD",
  116. };
  117. // for ARO : ad_impression 上报给firebase
  118. FirebaseHelper.logEvent("ad_impression", params);
  119. // for Taichi
  120. FirebaseHelper.logEvent("Ad_Impression_Revenue", params);
  121. // 累计超过0.01 USD 上报 Total_Ads_Revenue_001
  122. double previousTroasCache = Persistence().tRoasCache;
  123. double currentTroasCache = previousTroasCache + ad.revenue;
  124. if (currentTroasCache >= revenueThreshold) {
  125. FirebaseHelper.logEvent("Total_Ads_Revenue_001", {"value": currentTroasCache, "currency": "USD"});
  126. Persistence().tRoasCache = 0; // 缓存清零
  127. } else {
  128. Persistence().tRoasCache = currentTroasCache;
  129. }
  130. // adRevenue 事件上报给adjust
  131. AdjustHelper.trackAdRevenue(ad.placement, 1, ad.revenue, 'USD');
  132. // revenue 埋点时间上报给自主BI平台
  133. Statistics.postEvent({
  134. "project_id": Persistence().projectId,
  135. "user_id": Persistence().uuid,
  136. "library_name": Persistence().libraryName,
  137. "library_version": Persistence().packageVersion,
  138. "name": 'revenue',
  139. "tab_source": adSrc,
  140. "sku_id": skuId,
  141. "ad_src": adSrc,
  142. "ad_type": ad.placement,
  143. "ad_rev": ad.revenue,
  144. });
  145. }
  146. //////////////////////////// interstitialAd /////////////////////////////
  147. final int _maxExponentialRetryCount = 6;
  148. var _interstitialRetryAttempt = 0;
  149. ValueNotifier<AdState> interstitialAdState = ValueNotifier(AdState.initial);
  150. void initializeInterstitialAds() {
  151. AppLovinMAX.setInterstitialListener(
  152. InterstitialListener(
  153. onAdLoadedCallback: (ad) {
  154. // Interstitial ad is ready to show. AppLovinMAX.isInterstitialReady(_interstitial_ad_unit_ID) now returns 'true'.
  155. _log.info('Interstitial ad loaded from ${ad.networkName}');
  156. // Reset retry attempt
  157. _interstitialRetryAttempt = 0;
  158. interstitialAdState.value = AdState.ready;
  159. },
  160. onAdLoadFailedCallback: (adUnitId, error) {
  161. // Interstitial ad failed to load.
  162. // AppLovin recommends that you retry with exponentially higher delays up to a maximum delay (in this case 64 seconds).
  163. _interstitialRetryAttempt = _interstitialRetryAttempt + 1;
  164. if (_interstitialRetryAttempt > _maxExponentialRetryCount) return;
  165. int retryDelay = pow(2, min(_maxExponentialRetryCount, _interstitialRetryAttempt)).toInt();
  166. if (kDebugMode) {
  167. _log.info('Interstitial ad failed to load with code ${error.code} - retrying in ${retryDelay}s');
  168. }
  169. Future.delayed(Duration(milliseconds: retryDelay * 1000), () {
  170. AppLovinMAX.loadInterstitial(AdHelper.applovinInterstitialAdUnitId);
  171. });
  172. },
  173. onAdDisplayedCallback: (ad) {
  174. _log.info('interstitialAd displayed');
  175. interstitialAdState.value = AdState.showing; // 广告成功展示
  176. },
  177. onAdDisplayFailedCallback: (ad, error) {
  178. _log.info('interstitialAd display failed');
  179. interstitialAdState.value = AdState.error; // 广告显示异常
  180. },
  181. onAdClickedCallback: (ad) {},
  182. onAdHiddenCallback: (ad) {
  183. _log.info('interstitialAd hidden');
  184. interstitialAdState.value = AdState.dismissed; // 广告关闭
  185. AppLovinMAX.loadInterstitial(AdHelper.applovinInterstitialAdUnitId);
  186. },
  187. onAdRevenuePaidCallback: (ad) {
  188. _log.info('woooooooooo, applovin interstitial paid event: revenue: ${ad.revenue}, precision: ${ad.revenuePrecision}');
  189. if (ad.revenue > 0) {
  190. onAdRevenuePaid(ad); // revenue 单位转化为 valueMicro,以便和admod一致
  191. }
  192. },
  193. ),
  194. );
  195. // Load the first interstitial.
  196. Future.delayed(const Duration(seconds: 3), () {
  197. loadInterstitialAd();
  198. });
  199. }
  200. void loadInterstitialAd() async {
  201. if (!_hasInit) return;
  202. bool? isInit = await AppLovinMAX.isInitialized();
  203. if (isInit == null || !isInit) {
  204. return;
  205. }
  206. bool isReady = (await AppLovinMAX.isInterstitialReady(AdHelper.applovinInterstitialAdUnitId))!;
  207. if (isReady) {
  208. _log.info("applovin interstitial ad already ready, no need to load!");
  209. return;
  210. }
  211. AppLovinMAX.loadInterstitial(AdHelper.applovinInterstitialAdUnitId);
  212. }
  213. Future<bool> isInterstitialAdReady() async {
  214. if (!_hasInit) return false;
  215. try {
  216. bool? isInit = await AppLovinMAX.isInitialized();
  217. if (isInit == null || !isInit) {
  218. return false;
  219. }
  220. bool isReady = (await AppLovinMAX.isInterstitialReady(AdHelper.applovinInterstitialAdUnitId))!;
  221. return isReady;
  222. } catch (e) {
  223. _log.warning('isInterstitialReady error: $e');
  224. }
  225. return false;
  226. }
  227. String adSrc = "";
  228. String skuId = "";
  229. showInterstitialAd({String adSrc = "", String skuId = ""}) async {
  230. this.adSrc = adSrc;
  231. this.skuId = skuId;
  232. try {
  233. bool? isInit = await AppLovinMAX.isInitialized();
  234. if (isInit == null || !isInit) {
  235. return;
  236. }
  237. bool isReady = (await AppLovinMAX.isInterstitialReady(AdHelper.applovinInterstitialAdUnitId))!;
  238. if (isReady) {
  239. AppLovinMAX.showInterstitial(AdHelper.applovinInterstitialAdUnitId, placement: 'inters');
  240. } else {
  241. AppLovinMAX.loadInterstitial(AdHelper.applovinInterstitialAdUnitId);
  242. }
  243. } on PlatformException catch (e) {
  244. _log.warning('PlatformException: $e');
  245. } catch (e) {
  246. _log.warning('showInterstitialAd: $e');
  247. }
  248. }
  249. //////////////////////////// rewardedAd /////////////////////////////
  250. ValueNotifier<AdState> rewardedAdState = ValueNotifier(AdState.initial);
  251. var _rewardedAdRetryAttempt = 0;
  252. void initializeRewardedAd() {
  253. AppLovinMAX.setRewardedAdListener(
  254. RewardedAdListener(
  255. onAdLoadedCallback: (ad) {
  256. // Rewarded ad is ready to show. AppLovinMAX.isRewardedAdReady(_rewarded_ad_unit_ID) now returns 'true'.
  257. _log.info('Rewarded ad loaded from ${ad.networkName}');
  258. // Reset retry attempt
  259. _rewardedAdRetryAttempt = 0;
  260. rewardedAdState.value = AdState.ready;
  261. },
  262. onAdLoadFailedCallback: (adUnitId, error) {
  263. // Rewarded ad failed to load.
  264. // AppLovin recommends that you retry with exponentially higher delays up to a maximum delay (in this case 64 seconds).
  265. _rewardedAdRetryAttempt = _rewardedAdRetryAttempt + 1;
  266. if (_rewardedAdRetryAttempt > _maxExponentialRetryCount) return;
  267. int retryDelay = pow(2, min(_maxExponentialRetryCount, _rewardedAdRetryAttempt)).toInt();
  268. _log.info('Rewarded ad failed to load with code ${error.code} - retrying in ${retryDelay}s');
  269. Future.delayed(Duration(milliseconds: retryDelay * 1000), () {
  270. AppLovinMAX.loadRewardedAd(AdHelper.applovinRewardedAdUnitId);
  271. });
  272. },
  273. onAdDisplayedCallback: (ad) {
  274. _log.info('rewardedAd displayed');
  275. rewardedAdState.value = AdState.showing; // 广告成功展示
  276. },
  277. onAdDisplayFailedCallback: (ad, error) {
  278. _log.info('rewardedAd display failed');
  279. rewardedAdState.value = AdState.error; // 广告显示异常
  280. rewardCallback = null;
  281. },
  282. onAdClickedCallback: (ad) {},
  283. onAdHiddenCallback: (ad) {
  284. _log.info('rewardedAd hide');
  285. rewardedAdState.value = AdState.dismissed; // 广告关闭
  286. rewardCallback = null;
  287. AppLovinMAX.loadRewardedAd(AdHelper.applovinRewardedAdUnitId);
  288. },
  289. onAdReceivedRewardCallback: (ad, reward) {
  290. _log.info('rewardedAd receive reward: $reward');
  291. rewardCallback?.call(ad, reward);
  292. },
  293. onAdRevenuePaidCallback: (ad) {
  294. _log.info('woooooooooo, applovin rewarded paid event: revenue: ${ad.revenue} precision: ${ad.revenuePrecision}');
  295. if (ad.revenue > 0) {
  296. onAdRevenuePaid(ad); // revenue 单位转化为 valueMicro,以便和admod一致
  297. }
  298. },
  299. ),
  300. );
  301. // Load the first reward ad.
  302. // loadRewardedAd();
  303. Future.delayed(const Duration(seconds: 3), () {
  304. loadRewardedAd();
  305. });
  306. }
  307. void loadRewardedAd() async {
  308. if (!_hasInit) return;
  309. bool? isInit = await AppLovinMAX.isInitialized();
  310. if (isInit == null || !isInit) {
  311. _log.warning("applovin not initialized yet!");
  312. return;
  313. }
  314. bool isReady = (await AppLovinMAX.isRewardedAdReady(AdHelper.applovinRewardedAdUnitId))!;
  315. if (isReady) {
  316. _log.info("applovin reward ad already ready, no need to load!");
  317. return;
  318. }
  319. AppLovinMAX.loadRewardedAd(AdHelper.applovinRewardedAdUnitId);
  320. }
  321. Future<bool> isRewardedAdReady() async {
  322. if (!_hasInit) return false;
  323. try {
  324. bool? isInit = await AppLovinMAX.isInitialized();
  325. if (isInit == null || !isInit) {
  326. return false;
  327. }
  328. bool isReady = (await AppLovinMAX.isRewardedAdReady(AdHelper.applovinRewardedAdUnitId))!;
  329. return isReady;
  330. } catch (e) {
  331. _log.warning('isInterstitialReady error: $e');
  332. }
  333. return false;
  334. }
  335. Function(MaxAd, MaxReward)? rewardCallback;
  336. Future<bool> showRewardedlAd({required onUserEarnedReward, String adSrc = "", String skuId = ""}) async {
  337. this.adSrc = adSrc;
  338. this.skuId = skuId;
  339. rewardCallback = null;
  340. try {
  341. bool? isInit = await AppLovinMAX.isInitialized();
  342. if (isInit == null || !isInit) {
  343. return false;
  344. }
  345. bool isReady = (await AppLovinMAX.isRewardedAdReady(AdHelper.applovinRewardedAdUnitId))!;
  346. if (isReady) {
  347. AppLovinMAX.showRewardedAd(AdHelper.applovinRewardedAdUnitId, placement: 'reward');
  348. rewardCallback = onUserEarnedReward;
  349. return true;
  350. } else {
  351. AppLovinMAX.loadRewardedAd(AdHelper.applovinRewardedAdUnitId);
  352. return false;
  353. }
  354. } on PlatformException catch (e) {
  355. _log.warning('PlatformException: $e');
  356. return false;
  357. } catch (e) {
  358. _log.warning('showRewardedlAd error: $e');
  359. return false;
  360. }
  361. }
  362. }