applovin_ads_controller.dart 15 KB

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