applovin_ads_controller.dart 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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:io';
  6. import 'dart:math';
  7. import 'package:applovin_max/applovin_max.dart';
  8. import 'package:device_info_plus/device_info_plus.dart';
  9. import 'package:flutter/foundation.dart';
  10. import 'package:flutter/material.dart';
  11. import 'package:flutter/services.dart';
  12. import 'package:logging/logging.dart';
  13. import 'package:puzzleweave/ads/ad_helper.dart';
  14. import 'package:puzzleweave/firebase/adjust_helper.dart';
  15. import 'package:puzzleweave/firebase/firebase_helper.dart';
  16. import '../persistence/persistence.dart';
  17. import '../remote_config/remote_config.dart';
  18. import '../statistics/statistics.dart';
  19. final Logger _log = Logger('ApplovinAdsController');
  20. const int bannerReportDuration = 3 * 60 * 1000; // banner paid 3分钟报一次
  21. /// Allows showing ads. A facade for `package:google_mobile_ads`.
  22. class ApplovinAdsController {
  23. final BuildContext context;
  24. // 新增:设备保护标记
  25. bool _isLowRamDevice = false;
  26. bool _isProblematicDevice = false;
  27. bool get isLowRamDevice => _isLowRamDevice;
  28. // 从 Remote Config 获取设备黑名单
  29. Set<String> _getCrashProneDevices() {
  30. final blacklistStr = RemoteConfig().adCrashProneDevices;
  31. if (blacklistStr.isEmpty) return {};
  32. return blacklistStr.split(',').map((e) => e.trim().toLowerCase()).toSet();
  33. }
  34. bool _shouldSkipAds() {
  35. return _isLowRamDevice || _isProblematicDevice;
  36. }
  37. late double bannerPaidValueMicros; // banner广告累计收益
  38. late int lastBannerPaidReportTimestamp; // 上次banner广告收益上报时间戳,用于控制banner广告收益上报频率
  39. late double allPaidValueMicros; // 所有广告累计收益
  40. late double revenueThreshold; // 广告累计上报阈值
  41. bool _hasInit = false;
  42. bool get hasInit => _hasInit;
  43. final Completer<bool> completer = Completer();
  44. ApplovinAdsController(this.context);
  45. void dispose() {
  46. // 🔥 关键修复:防止内存泄漏
  47. if (!completer.isCompleted) {
  48. completer.complete(false);
  49. }
  50. // 清理状态通知器
  51. interstitialAdState.dispose();
  52. rewardedAdState.dispose();
  53. // 清理回调
  54. rewardCallback = null;
  55. }
  56. /// Initializes the injected [MobileAds.instance].
  57. Future<void> initialize() async {
  58. if (_hasInit) return;
  59. _log.info('AppLovinMAX.initialize...');
  60. // 1. 设备兼容性检测(关键:防止外部纹理崩溃)
  61. if (Platform.isAndroid) {
  62. final deviceInfo = DeviceInfoPlugin();
  63. final androidInfo = await deviceInfo.androidInfo;
  64. // 低端机检测
  65. _isLowRamDevice = androidInfo.isLowRamDevice || (androidInfo.systemFeatures.contains('android.hardware.ram.low'));
  66. // 问题设备检测(从 Remote Config 读取黑名单)
  67. String manufacturer = androidInfo.manufacturer.toLowerCase();
  68. String model = androidInfo.model.toLowerCase();
  69. final crashProneDevices = _getCrashProneDevices();
  70. _isProblematicDevice = crashProneDevices.any((device) => manufacturer.contains(device) || model.contains(device));
  71. if (_isProblematicDevice) {
  72. _log.warning('🔥 Problematic device detected: $manufacturer $model');
  73. }
  74. }
  75. // 用于模拟测试欧洲UMP是否正常,release版本注意注释掉
  76. // AppLovinMAX.setVerboseLogging(true);
  77. // AppLovinMAX.setConsentFlowDebugUserGeography(ConsentFlowUserGeography.gdpr);
  78. // 2. 开启合规流开关
  79. AppLovinMAX.setTermsAndPrivacyPolicyFlowEnabled(true);
  80. // 3. 设置你的隐私政策和用户协议链接(必须是有效的 URL)
  81. AppLovinMAX.setPrivacyPolicyUrl("https://longreachai.net/game/privacy_policy.html");
  82. AppLovinMAX.setTermsOfServiceUrl("https://longreachai.net/game/terms_of_service.html");
  83. // 4. 然后再初始化 SDK
  84. MaxConfiguration? sdkConfiguration = await AppLovinMAX.initialize(AdHelper.applovinSdkKey);
  85. _log.info('AppLovinMAX.initialize success!');
  86. lastBannerPaidReportTimestamp = Persistence().lastBannerPaidReportTimestamp;
  87. bannerPaidValueMicros = Persistence().bannerPaidValueMicros;
  88. allPaidValueMicros = Persistence().allPaidValueMicros;
  89. revenueThreshold = RemoteConfig().adRevenueThreshold;
  90. if (revenueThreshold <= 0.0) revenueThreshold = 0.01;
  91. // 5. 分步异步加载 (防止 FD 句柄数瞬间爆表)
  92. await Future.delayed(const Duration(milliseconds: 500));
  93. if (!_shouldSkipAds()) initializeBannerAds();
  94. await Future.delayed(const Duration(milliseconds: 500));
  95. if (!_shouldSkipAds()) initializeInterstitialAds();
  96. await Future.delayed(const Duration(milliseconds: 500));
  97. if (!_shouldSkipAds()) initializeRewardedAd();
  98. completer.complete(true);
  99. _hasInit = true;
  100. }
  101. void initializeBannerAds() {
  102. // 强制关闭低端机的自适应 Banner,因为其渲染开销极大
  103. AppLovinMAX.setBannerExtraParameter(AdHelper.applovinBannerAdUnitId, "adaptive_banner", _isLowRamDevice ? "false" : "true");
  104. }
  105. /// 强制销毁 Banner(解决 JNI CheckException 的大杀器)
  106. /// 在 AdsState dispose 或页面跳转前调用
  107. void destroyBanner() {
  108. _log.info("🔥 Explicitly destroying banner to release GPU buffers");
  109. try {
  110. // 强制通知原生层销毁 Banner 视图
  111. AppLovinMAX.destroyBanner(AdHelper.applovinBannerAdUnitId);
  112. } catch (e) {
  113. _log.warning("Destroy banner error: $e");
  114. }
  115. }
  116. Widget getBannerWidget(String positionKey) {
  117. // 增加:问题设备或未初始化,直接不渲染 Widget
  118. if (!_hasInit || _shouldSkipAds()) {
  119. return const SizedBox.shrink();
  120. }
  121. return MaxAdView(
  122. key: ValueKey(positionKey), // 只要 positionKey 不变,页面内刷新就不会重建
  123. adUnitId: AdHelper.applovinBannerAdUnitId,
  124. adFormat: AdFormat.banner,
  125. placement: 'banner',
  126. extraParameters: {'adaptive_banner': _isLowRamDevice ? 'false' : 'true'},
  127. listener: AdViewAdListener(
  128. onAdLoadedCallback: (ad) {
  129. // // 广告加载成功后, ad.size 包含实际的宽度和高度 (dp)
  130. // double? widthDp = ad.size?.width;
  131. // double? heightDp = ad.size?.height;
  132. // if (heightDp != null) {
  133. // context.read<Device>().bannerHeight = heightDp;
  134. // }
  135. // _log.info('banner广告 width = $widthDp, height = $heightDp');
  136. _log.info(() => 'applovin banner Ad loaded: ${ad.hashCode}');
  137. },
  138. onAdLoadFailedCallback: (adUnitId, error) {
  139. _log.warning('applovin banner Ad failedToLoad: $error');
  140. },
  141. onAdClickedCallback: (ad) {
  142. _log.info('applovin banner Ad click registered');
  143. },
  144. onAdExpandedCallback: (ad) {
  145. _log.info('applovin banner Ad expanded');
  146. },
  147. onAdCollapsedCallback: (ad) {
  148. _log.info('applovin banner Ad collaspsed');
  149. },
  150. onAdRevenuePaidCallback: (ad) {
  151. _log.info('woooooooooo, applovin banner paid event: revenue: ${ad.revenue} precision: ${ad.revenuePrecision}');
  152. if (ad.revenue > 0) {
  153. onAdRevenuePaid(ad); // revenue 单位转化为 valueMicro,以便和admod一致
  154. }
  155. },
  156. ),
  157. );
  158. }
  159. // revenue 回调处理,所有广告类型统一在此处理
  160. onAdRevenuePaid(MaxAd ad) async {
  161. _log.info('report ad revenue paid: ${ad.revenue}');
  162. Map<String, Object> params = {
  163. "ad_platform": 'appLovin',
  164. "ad_source": ad.networkName,
  165. "ad_format": ad.placement,
  166. "ad_unit_name": ad.adUnitId,
  167. "value": ad.revenue,
  168. "currency": "USD",
  169. };
  170. // for ARO : ad_impression 上报给firebase
  171. FirebaseHelper.logEvent("ad_impression", params);
  172. // for Taichi
  173. FirebaseHelper.logEvent("Ad_Impression_Revenue", params);
  174. // 累计超过0.01 USD 上报 Total_Ads_Revenue_001
  175. double previousTroasCache = Persistence().tRoasCache;
  176. double currentTroasCache = previousTroasCache + ad.revenue;
  177. if (currentTroasCache >= revenueThreshold) {
  178. FirebaseHelper.logEvent("Total_Ads_Revenue_001", {"value": currentTroasCache, "currency": "USD"});
  179. Persistence().tRoasCache = 0; // 缓存清零
  180. } else {
  181. Persistence().tRoasCache = currentTroasCache;
  182. }
  183. // adRevenue 事件上报给adjust
  184. AdjustHelper.trackAdRevenue(ad.placement, 1, ad.revenue, 'USD');
  185. // revenue 埋点时间上报给自主BI平台
  186. Statistics.postEvent({
  187. "project_id": Persistence().projectId,
  188. "user_id": Persistence().uuid,
  189. "library_name": Persistence().libraryName,
  190. "library_version": Persistence().packageVersion,
  191. "name": 'revenue',
  192. "tab_source": adSrc,
  193. "sku_id": skuId,
  194. "ad_src": adSrc,
  195. "ad_type": ad.placement,
  196. "ad_rev": ad.revenue,
  197. });
  198. }
  199. //////////////////////////// interstitialAd /////////////////////////////
  200. final int _maxExponentialRetryCount = 6;
  201. var _interstitialRetryAttempt = 0;
  202. ValueNotifier<AdState> interstitialAdState = ValueNotifier(AdState.initial);
  203. void initializeInterstitialAds() {
  204. AppLovinMAX.setInterstitialListener(
  205. InterstitialListener(
  206. onAdLoadedCallback: (ad) {
  207. // Interstitial ad is ready to show. AppLovinMAX.isInterstitialReady(_interstitial_ad_unit_ID) now returns 'true'.
  208. _log.info('Interstitial ad loaded from ${ad.networkName}');
  209. // Reset retry attempt
  210. _interstitialRetryAttempt = 0;
  211. interstitialAdState.value = AdState.ready;
  212. },
  213. onAdLoadFailedCallback: (adUnitId, error) {
  214. // Interstitial ad failed to load.
  215. // AppLovin recommends that you retry with exponentially higher delays up to a maximum delay (in this case 64 seconds).
  216. _interstitialRetryAttempt = _interstitialRetryAttempt + 1;
  217. if (_interstitialRetryAttempt > _maxExponentialRetryCount) return;
  218. int retryDelay = pow(2, min(_maxExponentialRetryCount, _interstitialRetryAttempt)).toInt();
  219. if (kDebugMode) {
  220. _log.info('Interstitial ad failed to load with code ${error.code} - retrying in ${retryDelay}s');
  221. }
  222. Future.delayed(Duration(milliseconds: retryDelay * 1000), () {
  223. AppLovinMAX.loadInterstitial(AdHelper.applovinInterstitialAdUnitId);
  224. });
  225. },
  226. onAdDisplayedCallback: (ad) {
  227. _log.info('interstitialAd displayed');
  228. interstitialAdState.value = AdState.showing; // 广告成功展示
  229. },
  230. onAdDisplayFailedCallback: (ad, error) {
  231. _log.info('interstitialAd display failed');
  232. interstitialAdState.value = AdState.error; // 广告显示异常
  233. },
  234. onAdClickedCallback: (ad) {},
  235. onAdHiddenCallback: (ad) {
  236. _log.info('interstitialAd hidden');
  237. interstitialAdState.value = AdState.dismissed; // 广告关闭
  238. AppLovinMAX.loadInterstitial(AdHelper.applovinInterstitialAdUnitId);
  239. },
  240. onAdRevenuePaidCallback: (ad) {
  241. _log.info('woooooooooo, applovin interstitial paid event: revenue: ${ad.revenue}, precision: ${ad.revenuePrecision}');
  242. if (ad.revenue > 0) {
  243. onAdRevenuePaid(ad); // revenue 单位转化为 valueMicro,以便和admod一致
  244. }
  245. },
  246. ),
  247. );
  248. // Load the first interstitial.
  249. Future.delayed(const Duration(seconds: 3), () {
  250. loadInterstitialAd();
  251. });
  252. }
  253. void loadInterstitialAd() async {
  254. if (!_hasInit) return;
  255. bool? isInit = await AppLovinMAX.isInitialized();
  256. if (isInit == null || !isInit) {
  257. return;
  258. }
  259. // 🔥 修复:安全解包
  260. bool? isReady = await AppLovinMAX.isInterstitialReady(AdHelper.applovinInterstitialAdUnitId);
  261. if (isReady == true) {
  262. _log.info("applovin interstitial ad already ready, no need to load!");
  263. return;
  264. }
  265. AppLovinMAX.loadInterstitial(AdHelper.applovinInterstitialAdUnitId);
  266. }
  267. Future<bool> isInterstitialAdReady() async {
  268. if (!_hasInit) return false;
  269. try {
  270. bool? isInit = await AppLovinMAX.isInitialized();
  271. if (isInit == null || !isInit) {
  272. return false;
  273. }
  274. // 🔥 修复:安全解包,防止崩溃
  275. bool? isReady = await AppLovinMAX.isInterstitialReady(AdHelper.applovinInterstitialAdUnitId);
  276. return isReady ?? false;
  277. } catch (e) {
  278. _log.warning('isInterstitialReady error: $e');
  279. }
  280. return false;
  281. }
  282. String adSrc = "";
  283. String skuId = "";
  284. showInterstitialAd({String adSrc = "", String skuId = ""}) async {
  285. this.adSrc = adSrc;
  286. this.skuId = skuId;
  287. // 🔥 新增:设备保护
  288. if (_shouldSkipAds()) {
  289. _log.info('🔥 Device protection: skipping interstitial ad');
  290. return;
  291. }
  292. try {
  293. bool? isInit = await AppLovinMAX.isInitialized();
  294. if (isInit == null || !isInit) {
  295. return;
  296. }
  297. // 🔥 修复:安全解包
  298. bool? isReady = await AppLovinMAX.isInterstitialReady(AdHelper.applovinInterstitialAdUnitId);
  299. if (isReady == true) {
  300. AppLovinMAX.showInterstitial(AdHelper.applovinInterstitialAdUnitId, placement: 'inters');
  301. } else {
  302. AppLovinMAX.loadInterstitial(AdHelper.applovinInterstitialAdUnitId);
  303. }
  304. } on PlatformException catch (e) {
  305. _log.warning('PlatformException: $e');
  306. } catch (e) {
  307. _log.warning('showInterstitialAd: $e');
  308. }
  309. }
  310. //////////////////////////// rewardedAd /////////////////////////////
  311. ValueNotifier<AdState> rewardedAdState = ValueNotifier(AdState.initial);
  312. var _rewardedAdRetryAttempt = 0;
  313. void initializeRewardedAd() {
  314. AppLovinMAX.setRewardedAdListener(
  315. RewardedAdListener(
  316. onAdLoadedCallback: (ad) {
  317. // Rewarded ad is ready to show. AppLovinMAX.isRewardedAdReady(_rewarded_ad_unit_ID) now returns 'true'.
  318. _log.info('Rewarded ad loaded from ${ad.networkName}');
  319. // Reset retry attempt
  320. _rewardedAdRetryAttempt = 0;
  321. rewardedAdState.value = AdState.ready;
  322. },
  323. onAdLoadFailedCallback: (adUnitId, error) {
  324. // Rewarded ad failed to load.
  325. // AppLovin recommends that you retry with exponentially higher delays up to a maximum delay (in this case 64 seconds).
  326. _rewardedAdRetryAttempt = _rewardedAdRetryAttempt + 1;
  327. if (_rewardedAdRetryAttempt > _maxExponentialRetryCount) return;
  328. int retryDelay = pow(2, min(_maxExponentialRetryCount, _rewardedAdRetryAttempt)).toInt();
  329. _log.info('Rewarded ad failed to load with code ${error.code} - retrying in ${retryDelay}s');
  330. Future.delayed(Duration(milliseconds: retryDelay * 1000), () {
  331. AppLovinMAX.loadRewardedAd(AdHelper.applovinRewardedAdUnitId);
  332. });
  333. },
  334. onAdDisplayedCallback: (ad) {
  335. _log.info('rewardedAd displayed');
  336. rewardedAdState.value = AdState.showing; // 广告成功展示
  337. },
  338. onAdDisplayFailedCallback: (ad, error) {
  339. _log.info('rewardedAd display failed');
  340. rewardedAdState.value = AdState.error; // 广告显示异常
  341. rewardCallback = null;
  342. },
  343. onAdClickedCallback: (ad) {},
  344. onAdHiddenCallback: (ad) {
  345. _log.info('rewardedAd hide');
  346. rewardedAdState.value = AdState.dismissed; // 广告关闭
  347. rewardCallback = null;
  348. AppLovinMAX.loadRewardedAd(AdHelper.applovinRewardedAdUnitId);
  349. },
  350. onAdReceivedRewardCallback: (ad, reward) {
  351. _log.info('rewardedAd receive reward: $reward');
  352. rewardCallback?.call(ad, reward);
  353. },
  354. onAdRevenuePaidCallback: (ad) {
  355. _log.info('woooooooooo, applovin rewarded paid event: revenue: ${ad.revenue} precision: ${ad.revenuePrecision}');
  356. if (ad.revenue > 0) {
  357. onAdRevenuePaid(ad); // revenue 单位转化为 valueMicro,以便和admod一致
  358. }
  359. },
  360. ),
  361. );
  362. // Load the first reward ad.
  363. // loadRewardedAd();
  364. Future.delayed(const Duration(seconds: 3), () {
  365. loadRewardedAd();
  366. });
  367. }
  368. void loadRewardedAd() async {
  369. if (!_hasInit) return;
  370. bool? isInit = await AppLovinMAX.isInitialized();
  371. if (isInit == null || !isInit) {
  372. _log.warning("applovin not initialized yet!");
  373. return;
  374. }
  375. // 🔥 修复:安全解包
  376. bool? isReady = await AppLovinMAX.isRewardedAdReady(AdHelper.applovinRewardedAdUnitId);
  377. if (isReady == true) {
  378. _log.info("applovin reward ad already ready, no need to load!");
  379. return;
  380. }
  381. AppLovinMAX.loadRewardedAd(AdHelper.applovinRewardedAdUnitId);
  382. }
  383. Future<bool> isRewardedAdReady() async {
  384. if (!_hasInit) return false;
  385. try {
  386. bool? isInit = await AppLovinMAX.isInitialized();
  387. if (isInit == null || !isInit) {
  388. return false;
  389. }
  390. // 🔥 修复:安全解包
  391. bool? isReady = await AppLovinMAX.isRewardedAdReady(AdHelper.applovinRewardedAdUnitId);
  392. return isReady ?? false;
  393. } catch (e) {
  394. _log.warning('isRewardedAdReady error: $e');
  395. }
  396. return false;
  397. }
  398. Function(MaxAd, MaxReward)? rewardCallback;
  399. Future<bool> showRewardedlAd({required onUserEarnedReward, String adSrc = "", String skuId = ""}) async {
  400. this.adSrc = adSrc;
  401. this.skuId = skuId;
  402. rewardCallback = null;
  403. try {
  404. bool? isInit = await AppLovinMAX.isInitialized();
  405. if (isInit == null || !isInit) {
  406. return false;
  407. }
  408. // 🔥 修复:安全解包
  409. bool? isReady = await AppLovinMAX.isRewardedAdReady(AdHelper.applovinRewardedAdUnitId);
  410. if (isReady == true) {
  411. AppLovinMAX.showRewardedAd(AdHelper.applovinRewardedAdUnitId, placement: 'reward');
  412. rewardCallback = onUserEarnedReward;
  413. return true;
  414. } else {
  415. AppLovinMAX.loadRewardedAd(AdHelper.applovinRewardedAdUnitId);
  416. return false;
  417. }
  418. } on PlatformException catch (e) {
  419. _log.warning('PlatformException: $e');
  420. return false;
  421. } catch (e) {
  422. _log.warning('showRewardedlAd error: $e');
  423. return false;
  424. }
  425. }
  426. }