applovin_ads_controller.dart 19 KB

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