applovin_ads_controller.dart 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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:provider/provider.dart';
  12. import 'package:puzzleweave/ads/ad_helper.dart';
  13. import 'package:puzzleweave/config/device.dart';
  14. import 'package:puzzleweave/firebase/firebase_helper.dart';
  15. import '../persistence/persistence.dart';
  16. import '../remote_config/remote_config.dart';
  17. import '../statistics/statistics.dart';
  18. final Logger _log = Logger('ApplovinAdsController');
  19. const int bannerReportDuration = 3 * 60 * 1000; // banner paid 3分钟报一次
  20. /// Allows showing ads. A facade for `package:google_mobile_ads`.
  21. class ApplovinAdsController {
  22. final BuildContext context;
  23. late double bannerPaidValueMicros; // banner广告累计收益
  24. late int lastBannerPaidReportTimestamp; // 上次banner广告收益上报时间戳,用于控制banner广告收益上报频率
  25. late double allPaidValueMicros; // 所有广告累计收益
  26. late double revenueThreshold; // 广告累计上报阈值
  27. bool _hasInit = false;
  28. bool get hasInit => _hasInit;
  29. final Completer<bool> completer = Completer();
  30. /// Creates an [ApplovinAdsController] that wraps around a [MobileAds] [instance].
  31. ///
  32. /// Example usage:
  33. ///
  34. /// var controller = ApplovinAdsController(MobileAds.instance);
  35. ApplovinAdsController(this.context);
  36. void dispose() {}
  37. /// Initializes the injected [MobileAds.instance].
  38. Future<void> initialize() async {
  39. if (_hasInit) return;
  40. _log.info('AppLovinMAX.initialize...');
  41. MaxConfiguration? sdkConfiguration = await AppLovinMAX.initialize(AdHelper.applovinSdkKey);
  42. _log.info('AppLovinMAX.initialize success!');
  43. lastBannerPaidReportTimestamp = Persistence().lastBannerPaidReportTimestamp;
  44. bannerPaidValueMicros = Persistence().bannerPaidValueMicros;
  45. allPaidValueMicros = Persistence().allPaidValueMicros;
  46. revenueThreshold = RemoteConfig().adRevenueThreshold;
  47. if (revenueThreshold <= 0.0) revenueThreshold = 0.01;
  48. initializeBannerAds();
  49. initializeInterstitialAds();
  50. initializeRewardedAd();
  51. completer.complete(true);
  52. _hasInit = true;
  53. }
  54. void initializeBannerAds() {
  55. AppLovinMAX.setBannerExtraParameter(AdHelper.applovinBannerAdUnitId, "adaptive_banner", "true");
  56. // MAX automatically sizes banners to 320×50 on phones and 728×90 on tablets
  57. // 移除这一行,避免与 MaxAdView Widget 冲突!
  58. // AppLovin MAX 在 Flutter 中的最佳实践是只使用 MaxAdView Widget,让 Flutter 来管理 Banner 视图的布局和生命周期
  59. // 同时调用 AppLovinMAX.createBanner (原生创建) 和渲染 MaxAdView (Flutter Widget),特别是在 iOS 上,原生层可能会意外地创建了一个透明的全屏视图来管理广告
  60. // AppLovinMAX.createBanner(AdHelper.applovinBannerAdUnitId, AdViewPosition.bottomCenter);
  61. }
  62. Widget get bannerAdWidget => MaxAdView(
  63. adUnitId: AdHelper.applovinBannerAdUnitId,
  64. adFormat: AdFormat.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. onBannerAdPaid(ad.revenue * 1000000, 'USD', ad); // revenue 单位转化为 valueMicro,以便和admod一致
  93. }
  94. },
  95. ),
  96. );
  97. // banner广告收益回调的处理
  98. onBannerAdPaid(double valueMicros, String currencyCode, MaxAd ad) async {
  99. // 原来的逻辑
  100. bannerPaidValueMicros += valueMicros;
  101. int nowTimestamp = DateTime.now().millisecondsSinceEpoch;
  102. if ((nowTimestamp - lastBannerPaidReportTimestamp) >= bannerReportDuration) {
  103. _log.info('report banner ad paid: ${bannerPaidValueMicros / 1000000}$currencyCode');
  104. FirebaseHelper.logEvent("ad_impression", {
  105. "ad_count": 1,
  106. "ad_platform": 'appLovin',
  107. "ad_source": ad.networkName,
  108. "ad_format": 'banner',
  109. "ad_unit_name": ad.adUnitId,
  110. "value": bannerPaidValueMicros / 1000000,
  111. "currency": "USD",
  112. });
  113. Statistics.postEvent({
  114. "project_id": Persistence().projectId,
  115. "user_id": Persistence().uuid,
  116. "library_name": Persistence().libraryName,
  117. "library_version": Persistence().packageVersion,
  118. "name": "revenue",
  119. "sku_id": '',
  120. "tab_source": 'play',
  121. "ad_src": 'play',
  122. "ad_count": bannerPaidValueMicros ~/ valueMicros,
  123. "ad_type": 'banner',
  124. "ad_rev": bannerPaidValueMicros / 1000000,
  125. });
  126. bannerPaidValueMicros = 0; // 累计清零
  127. lastBannerPaidReportTimestamp = nowTimestamp;
  128. Persistence().lastBannerPaidReportTimestamp = lastBannerPaidReportTimestamp;
  129. }
  130. Persistence().bannerPaidValueMicros = bannerPaidValueMicros;
  131. // 新的逻辑, 累计收益超过规定阈值,上报firebase和appsflyer
  132. allPaidValueMicros += valueMicros;
  133. if ((allPaidValueMicros / 1000000) >= revenueThreshold) {
  134. _log.info('report all ad paid: ${allPaidValueMicros / 1000000}$currencyCode');
  135. FirebaseHelper.logEvent("ad_paid", {"currency": currencyCode, "value": allPaidValueMicros / 1000000});
  136. // AppsflyerHelper.logEvent("ad_paid", {"af_currency": currencyCode, "af_revenue": allPaidValueMicros / 1000000});
  137. allPaidValueMicros = 0; // 累计清零
  138. }
  139. Persistence().allPaidValueMicros = allPaidValueMicros;
  140. }
  141. //////////////////////////// interstitialAd /////////////////////////////
  142. final int _maxExponentialRetryCount = 6;
  143. var _interstitialRetryAttempt = 0;
  144. ValueNotifier<AdState> interstitialAdState = ValueNotifier(AdState.initial);
  145. void initializeInterstitialAds() {
  146. AppLovinMAX.setInterstitialListener(
  147. InterstitialListener(
  148. onAdLoadedCallback: (ad) {
  149. // Interstitial ad is ready to show. AppLovinMAX.isInterstitialReady(_interstitial_ad_unit_ID) now returns 'true'.
  150. _log.info('Interstitial ad loaded from ${ad.networkName}');
  151. // Reset retry attempt
  152. _interstitialRetryAttempt = 0;
  153. interstitialAdState.value = AdState.ready;
  154. },
  155. onAdLoadFailedCallback: (adUnitId, error) {
  156. // Interstitial ad failed to load.
  157. // AppLovin recommends that you retry with exponentially higher delays up to a maximum delay (in this case 64 seconds).
  158. _interstitialRetryAttempt = _interstitialRetryAttempt + 1;
  159. if (_interstitialRetryAttempt > _maxExponentialRetryCount) return;
  160. int retryDelay = pow(2, min(_maxExponentialRetryCount, _interstitialRetryAttempt)).toInt();
  161. if (kDebugMode) {
  162. _log.info('Interstitial ad failed to load with code ${error.code} - retrying in ${retryDelay}s');
  163. }
  164. Future.delayed(Duration(milliseconds: retryDelay * 1000), () {
  165. AppLovinMAX.loadInterstitial(AdHelper.applovinInterstitialAdUnitId);
  166. });
  167. },
  168. onAdDisplayedCallback: (ad) {
  169. _log.info('interstitialAd displayed');
  170. interstitialAdState.value = AdState.showing; // 广告成功展示
  171. },
  172. onAdDisplayFailedCallback: (ad, error) {
  173. _log.info('interstitialAd display failed');
  174. interstitialAdState.value = AdState.error; // 广告显示异常
  175. },
  176. onAdClickedCallback: (ad) {},
  177. onAdHiddenCallback: (ad) {
  178. _log.info('interstitialAd hidden');
  179. interstitialAdState.value = AdState.dismissed; // 广告关闭
  180. AppLovinMAX.loadInterstitial(AdHelper.applovinInterstitialAdUnitId);
  181. },
  182. onAdRevenuePaidCallback: (ad) {
  183. _log.info('woooooooooo, applovin interstitial paid event: revenue: ${ad.revenue}, precision: ${ad.revenuePrecision}');
  184. if (ad.revenue > 0) {
  185. onInterstitialAdPaid(ad.revenue * 1000000, 'USD', ad); // revenue 单位转化为 valueMicro,以便和admod一致
  186. }
  187. },
  188. ),
  189. );
  190. // Load the first interstitial.
  191. Future.delayed(const Duration(seconds: 3), () {
  192. loadInterstitialAd();
  193. });
  194. }
  195. void loadInterstitialAd() async {
  196. if (!_hasInit) return;
  197. bool? isInit = await AppLovinMAX.isInitialized();
  198. if (isInit == null || !isInit) {
  199. return;
  200. }
  201. bool isReady = (await AppLovinMAX.isInterstitialReady(AdHelper.applovinInterstitialAdUnitId))!;
  202. if (isReady) {
  203. _log.info("applovin interstitial ad already ready, no need to load!");
  204. return;
  205. }
  206. AppLovinMAX.loadInterstitial(AdHelper.applovinInterstitialAdUnitId);
  207. }
  208. Future<bool> isInterstitialAdReady() async {
  209. if (!_hasInit) return false;
  210. try {
  211. bool? isInit = await AppLovinMAX.isInitialized();
  212. if (isInit == null || !isInit) {
  213. return false;
  214. }
  215. bool isReady = (await AppLovinMAX.isInterstitialReady(AdHelper.applovinInterstitialAdUnitId))!;
  216. return isReady;
  217. } catch (e) {
  218. _log.warning('isInterstitialReady error: $e');
  219. }
  220. return false;
  221. }
  222. String adSrc = "";
  223. String skuId = "";
  224. showInterstitialAd({String adSrc = "", String skuId = ""}) async {
  225. this.adSrc = adSrc;
  226. this.skuId = skuId;
  227. try {
  228. bool? isInit = await AppLovinMAX.isInitialized();
  229. if (isInit == null || !isInit) {
  230. return;
  231. }
  232. bool isReady = (await AppLovinMAX.isInterstitialReady(AdHelper.applovinInterstitialAdUnitId))!;
  233. if (isReady) {
  234. AppLovinMAX.showInterstitial(AdHelper.applovinInterstitialAdUnitId);
  235. } else {
  236. AppLovinMAX.loadInterstitial(AdHelper.applovinInterstitialAdUnitId);
  237. }
  238. } on PlatformException catch (e) {
  239. _log.warning('PlatformException: $e');
  240. } catch (e) {
  241. _log.warning('showInterstitialAd: $e');
  242. }
  243. }
  244. onInterstitialAdPaid(double valueMicros, String currencyCode, MaxAd ad) async {
  245. // 老的逻辑,每次收益都上报
  246. _log.info('report interstitial ad paid: ${valueMicros / 1000000}$currencyCode');
  247. FirebaseHelper.logEvent("ad_impression", {
  248. "ad_count": 1,
  249. "ad_platform": 'appLovin',
  250. "ad_source": ad.networkName,
  251. "ad_format": 'inters',
  252. "ad_unit_name": ad.adUnitId,
  253. "value": valueMicros / 1000000,
  254. "currency": "USD",
  255. });
  256. Statistics.postEvent({
  257. "project_id": Persistence().projectId,
  258. "user_id": Persistence().uuid,
  259. "library_name": Persistence().libraryName,
  260. "library_version": Persistence().packageVersion,
  261. "name": 'revenue',
  262. "tab_source": adSrc,
  263. "sku_id": skuId,
  264. "ad_src": adSrc,
  265. "ad_count": 1,
  266. "ad_type": "inters",
  267. "ad_rev": valueMicros / 1000000,
  268. });
  269. // 新的逻辑, 累计收益超过规定阈值,上报firebase和appsflyer
  270. allPaidValueMicros += valueMicros;
  271. if ((allPaidValueMicros / 1000000) >= revenueThreshold) {
  272. _log.info('report all ad paid: ${allPaidValueMicros / 1000000}$currencyCode');
  273. FirebaseHelper.logEvent("ad_paid", {"currency": currencyCode, "value": allPaidValueMicros / 1000000});
  274. // AppsflyerHelper.logEvent("ad_paid", {"af_currency": currencyCode, "af_revenue": allPaidValueMicros / 1000000});
  275. allPaidValueMicros = 0; // 累计清零
  276. }
  277. Persistence().allPaidValueMicros = allPaidValueMicros;
  278. }
  279. //////////////////////////// rewardedAd /////////////////////////////
  280. ValueNotifier<AdState> rewardedAdState = ValueNotifier(AdState.initial);
  281. var _rewardedAdRetryAttempt = 0;
  282. void initializeRewardedAd() {
  283. AppLovinMAX.setRewardedAdListener(
  284. RewardedAdListener(
  285. onAdLoadedCallback: (ad) {
  286. // Rewarded ad is ready to show. AppLovinMAX.isRewardedAdReady(_rewarded_ad_unit_ID) now returns 'true'.
  287. _log.info('Rewarded ad loaded from ${ad.networkName}');
  288. // Reset retry attempt
  289. _rewardedAdRetryAttempt = 0;
  290. rewardedAdState.value = AdState.ready;
  291. },
  292. onAdLoadFailedCallback: (adUnitId, error) {
  293. // Rewarded ad failed to load.
  294. // AppLovin recommends that you retry with exponentially higher delays up to a maximum delay (in this case 64 seconds).
  295. _rewardedAdRetryAttempt = _rewardedAdRetryAttempt + 1;
  296. if (_rewardedAdRetryAttempt > _maxExponentialRetryCount) return;
  297. int retryDelay = pow(2, min(_maxExponentialRetryCount, _rewardedAdRetryAttempt)).toInt();
  298. _log.info('Rewarded ad failed to load with code ${error.code} - retrying in ${retryDelay}s');
  299. Future.delayed(Duration(milliseconds: retryDelay * 1000), () {
  300. AppLovinMAX.loadRewardedAd(AdHelper.applovinRewardedAdUnitId);
  301. });
  302. },
  303. onAdDisplayedCallback: (ad) {
  304. _log.info('rewardedAd displayed');
  305. rewardedAdState.value = AdState.showing; // 广告成功展示
  306. },
  307. onAdDisplayFailedCallback: (ad, error) {
  308. _log.info('rewardedAd display failed');
  309. rewardedAdState.value = AdState.error; // 广告显示异常
  310. rewardCallback = null;
  311. },
  312. onAdClickedCallback: (ad) {},
  313. onAdHiddenCallback: (ad) {
  314. _log.info('rewardedAd hide');
  315. rewardedAdState.value = AdState.dismissed; // 广告关闭
  316. rewardCallback = null;
  317. AppLovinMAX.loadRewardedAd(AdHelper.applovinRewardedAdUnitId);
  318. },
  319. onAdReceivedRewardCallback: (ad, reward) {
  320. _log.info('rewardedAd receive reward: $reward');
  321. rewardCallback?.call(ad, reward);
  322. },
  323. onAdRevenuePaidCallback: (ad) {
  324. _log.info('woooooooooo, applovin rewarded paid event: revenue: ${ad.revenue} precision: ${ad.revenuePrecision}');
  325. if (ad.revenue > 0) {
  326. onRewardedAdPaid(ad.revenue * 1000000, 'USD', ad); // revenue 单位转化为 valueMicro,以便和admod一致
  327. }
  328. },
  329. ),
  330. );
  331. // Load the first reward ad.
  332. // loadRewardedAd();
  333. Future.delayed(const Duration(seconds: 3), () {
  334. loadRewardedAd();
  335. });
  336. }
  337. void loadRewardedAd() async {
  338. if (!_hasInit) return;
  339. bool? isInit = await AppLovinMAX.isInitialized();
  340. if (isInit == null || !isInit) {
  341. _log.warning("applovin not initialized yet!");
  342. return;
  343. }
  344. bool isReady = (await AppLovinMAX.isRewardedAdReady(AdHelper.applovinRewardedAdUnitId))!;
  345. if (isReady) {
  346. _log.info("applovin reward ad already ready, no need to load!");
  347. return;
  348. }
  349. AppLovinMAX.loadRewardedAd(AdHelper.applovinRewardedAdUnitId);
  350. }
  351. Future<bool> isRewardedAdReady() async {
  352. if (!_hasInit) return false;
  353. try {
  354. bool? isInit = await AppLovinMAX.isInitialized();
  355. if (isInit == null || !isInit) {
  356. return false;
  357. }
  358. bool isReady = (await AppLovinMAX.isRewardedAdReady(AdHelper.applovinRewardedAdUnitId))!;
  359. return isReady;
  360. } catch (e) {
  361. _log.warning('isInterstitialReady error: $e');
  362. }
  363. return false;
  364. }
  365. Function(MaxAd, MaxReward)? rewardCallback;
  366. Future<bool> showRewardedlAd({required onUserEarnedReward, String adSrc = "", String skuId = ""}) async {
  367. this.adSrc = adSrc;
  368. this.skuId = skuId;
  369. rewardCallback = null;
  370. try {
  371. bool? isInit = await AppLovinMAX.isInitialized();
  372. if (isInit == null || !isInit) {
  373. return false;
  374. }
  375. bool isReady = (await AppLovinMAX.isRewardedAdReady(AdHelper.applovinRewardedAdUnitId))!;
  376. if (isReady) {
  377. AppLovinMAX.showRewardedAd(AdHelper.applovinRewardedAdUnitId);
  378. rewardCallback = onUserEarnedReward;
  379. return true;
  380. } else {
  381. AppLovinMAX.loadRewardedAd(AdHelper.applovinRewardedAdUnitId);
  382. return false;
  383. }
  384. } on PlatformException catch (e) {
  385. _log.warning('PlatformException: $e');
  386. return false;
  387. } catch (e) {
  388. _log.warning('showRewardedlAd error: $e');
  389. return false;
  390. }
  391. }
  392. onRewardedAdPaid(double valueMicros, String currencyCode, MaxAd ad) async {
  393. // 老的逻辑,每次收益都上报
  394. _log.info('report rewarded ad paid: ${valueMicros / 1000000}$currencyCode');
  395. FirebaseHelper.logEvent("ad_impression", {
  396. "ad_count": 1,
  397. "ad_platform": 'appLovin',
  398. "ad_source": ad.networkName,
  399. "ad_format": 'reward',
  400. "ad_unit_name": ad.adUnitId,
  401. "value": valueMicros / 1000000,
  402. "currency": "USD",
  403. });
  404. Statistics.postEvent({
  405. "project_id": Persistence().projectId,
  406. "user_id": Persistence().uuid,
  407. "library_name": Persistence().libraryName,
  408. "library_version": Persistence().packageVersion,
  409. "name": 'revenue',
  410. "tab_source": adSrc,
  411. "sku_id": skuId,
  412. "ad_src": adSrc,
  413. "ad_count": 1,
  414. "ad_type": "reward",
  415. "ad_rev": valueMicros / 1000000,
  416. });
  417. // 新的逻辑, 累计收益超过规定阈值,上报firebase和appsflyer
  418. allPaidValueMicros += valueMicros;
  419. if ((allPaidValueMicros / 1000000) >= revenueThreshold) {
  420. _log.info('report all ad paid: ${allPaidValueMicros / 1000000}$currencyCode');
  421. FirebaseHelper.logEvent("ad_paid", {"currency": currencyCode, "value": allPaidValueMicros / 1000000});
  422. // AppsflyerHelper.logEvent("ad_paid", {"af_currency": currencyCode, "af_revenue": allPaidValueMicros / 1000000});
  423. allPaidValueMicros = 0; // 累计清零
  424. }
  425. Persistence().allPaidValueMicros = allPaidValueMicros;
  426. }
  427. }