applovin_ads_controller.dart 15 KB

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