home_screen.dart 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'dart:math';
  4. import 'package:app_tracking_transparency/app_tracking_transparency.dart';
  5. import 'package:firebase_crashlytics/firebase_crashlytics.dart';
  6. import 'package:firebase_messaging/firebase_messaging.dart';
  7. import 'package:flutter/material.dart';
  8. import 'package:flutter_svg/svg.dart';
  9. import 'package:fluttertoast/fluttertoast.dart';
  10. import 'package:logging/logging.dart';
  11. import 'package:lottie/lottie.dart';
  12. import 'package:provider/provider.dart';
  13. import 'package:puzzleweave/ads/applovin_ads_controller.dart';
  14. import 'package:puzzleweave/audio/jc_audio_controller.dart';
  15. import 'package:puzzleweave/collection/collection_screen.dart';
  16. import 'package:puzzleweave/config/config.dart';
  17. import 'package:puzzleweave/config/device.dart';
  18. import 'package:puzzleweave/firebase/adjust_helper.dart';
  19. import 'package:puzzleweave/homepage/home_board_play.dart';
  20. import 'package:puzzleweave/l10n/app_localizations.dart';
  21. import 'package:puzzleweave/models/cached_request.dart';
  22. import 'package:puzzleweave/models/data.dart';
  23. import 'package:puzzleweave/models/download.dart';
  24. import 'package:puzzleweave/models/items.dart';
  25. import 'package:puzzleweave/persistence/persistence.dart';
  26. import 'package:puzzleweave/platform/my_method_channel.dart';
  27. import 'package:puzzleweave/play/board_play.dart';
  28. import 'package:puzzleweave/settings/settings_screen.dart';
  29. import 'package:puzzleweave/skin/skin.dart';
  30. import 'package:puzzleweave/utils/mybutton.dart';
  31. import 'package:puzzleweave/utils/utils.dart';
  32. import '../ads/ads_state.dart';
  33. final Logger _log = Logger('home_screen');
  34. class HomeScreen extends StatefulWidget {
  35. const HomeScreen({super.key});
  36. @override
  37. State<StatefulWidget> createState() => _HomeScreen();
  38. }
  39. const int minimumRemoteLoadCount = 30; // 假设加载到 30 张图才算网络畅通
  40. class _HomeScreen extends AdsState<HomeScreen> with TickerProviderStateMixin {
  41. late Device device;
  42. late JcAudioController audio;
  43. late Data data;
  44. List<ListItem>? latest;
  45. late CachedRequest latestCachedRequest;
  46. late StreamSubscription? latestSubscription;
  47. // 自定义画布控制器(可选,用于控制画布绘制逻辑)
  48. final _canvasKey = GlobalKey<HomeBoardPlayState>();
  49. // !!! 新增:用于定位 Collection 按钮的 GlobalKey
  50. final GlobalKey _collectionKey = GlobalKey();
  51. bool isLoading = true;
  52. // !!! 新增:Collection 按钮的动画控制器和动画
  53. late AnimationController _collectionController; // 左上角 collection button 的动画控制器
  54. late Animation<double> _collectionAnimation; // 放大/缩小动画
  55. bool firstRun = false;
  56. @override
  57. void initState() {
  58. super.initState();
  59. _log.info("首页初始化");
  60. // 在组件绘制后检查 firstRun 并导航
  61. if (Persistence().firstRun) {
  62. firstRun = true;
  63. WidgetsBinding.instance.addPostFrameCallback((_) {
  64. // 仅当未跳转过时执行
  65. _handleFirstRunNavigation();
  66. });
  67. Persistence().firstRun = false;
  68. }
  69. device = context.read<Device>();
  70. audio = context.read<JcAudioController>();
  71. data = context.read<Data>();
  72. latestCachedRequest = data.latest;
  73. // 主动获取缓存数据(关键)
  74. final cachedData = latestCachedRequest.cachedData;
  75. if (cachedData != null) {
  76. _onLatestDataUpdate(cachedData);
  77. }
  78. latestSubscription = latestCachedRequest.stream.listen(_onLatestDataUpdate, onError: _onLatestDataError);
  79. // !!! 改造点 1: 初始化 Collection 按钮动画
  80. _collectionController =
  81. AnimationController(
  82. // 设定总时长
  83. duration: const Duration(milliseconds: 300),
  84. vsync: this,
  85. )..addStatusListener((status) {
  86. if (status == AnimationStatus.completed) {
  87. audio.playSfx(SfxType.pop);
  88. }
  89. });
  90. // !!! 改造点 2: 使用 TweenSequence 实现平滑的放大和缩小
  91. _collectionAnimation = TweenSequence<double>([
  92. // 阶段 1: 放大到 1.3 (占总时长的 50%)
  93. TweenSequenceItem(tween: Tween<double>(begin: 1.0, end: 1.4).chain(CurveTween(curve: Curves.easeOut)), weight: 40.0),
  94. // 阶段 2: 缩小回 1.0 (占总时长的 50%)
  95. TweenSequenceItem(tween: Tween<double>(begin: 1.4, end: 1.0).chain(CurveTween(curve: Curves.easeIn)), weight: 60.0),
  96. ]).animate(_collectionController);
  97. audio.startMusic();
  98. }
  99. // 首页初始化之后的跳转,首次运行直接进入play页面,上次从play页面退出有缓存存在也跳转到play页面
  100. void _handleFirstRunNavigation() async {
  101. _log.info('First run detected, navigating to initial play page.');
  102. final AssetItem initialItem = AssetItem(
  103. Config.firstId,
  104. '',
  105. 2000,
  106. 3000,
  107. 3,
  108. false,
  109. 'assets/builtin/${Config.firstId}.jpeg',
  110. 'assets/builtin/${Config.firstId}.jpeg',
  111. );
  112. return gotoPlay(initialItem, firstRun: true);
  113. }
  114. // 检查是否需要跳转到boardplay
  115. void checkGoPlay() async {
  116. if (currentItem != null) {
  117. final jsonFile = await localFile(currentItem!.jsonPath);
  118. final exists = await jsonFile.exists();
  119. // !!! 关键修复:检查当前组件是否还在组件树中
  120. if (!mounted) return;
  121. if (exists) {
  122. gotoPlay(currentItem!);
  123. }
  124. }
  125. }
  126. @override
  127. void dispose() {
  128. latestSubscription?.cancel();
  129. _collectionController.dispose();
  130. super.dispose();
  131. }
  132. _onLatestDataUpdate(datalist) {
  133. _log.info('_onLatestDataUpdate.... ');
  134. if (datalist != null) {
  135. bool check = false;
  136. if (currentItem == null && datalist != null && !firstRun) {
  137. check = true;
  138. }
  139. latest = datalist as List<ListItem>;
  140. isLoading = false;
  141. setState(() {});
  142. // 1. 检查数据量是否达到最低要求 (>= 30)
  143. final bool hasSufficientData = datalist.length >= minimumRemoteLoadCount;
  144. // 2. 检查数据是否来自最近一次成功的网络请求
  145. final bool isNetworkActive = latestCachedRequest.hasRecentSuccessfulFetch; // !!! 关键检查点
  146. if (hasSufficientData) {
  147. // 如果数据完整,无论是否是缓存数据,都尝试初始化第三方服务(因为主页已经可以显示了)
  148. if (!hasInit) {
  149. initThird();
  150. }
  151. // !!! 核心修改:只有在数据完整且最近网络请求成功时,才启动预加载
  152. if (isNetworkActive) {
  153. _log.info('Data sufficient AND Network Active. Starting preload.');
  154. Future.delayed(const Duration(seconds: 3), () => _preloadNextImages());
  155. } else {
  156. // 数据完整,但来自缓存,网络状态未知,3秒后尝试刷新(refresh)
  157. _log.info('Data sufficient BUT Network status unknown/inactive. Attempting refresh in 3s.');
  158. Future.delayed(Duration(seconds: 3), () => refresh());
  159. }
  160. } else {
  161. // 数据不足 (例如,只有内置图),无论是缓存还是远程失败,都需要重试
  162. _log.info('Data insufficient (only ${datalist.length} items). Attempting refresh in 3s.');
  163. Future.delayed(Duration(seconds: 3), () => refresh());
  164. }
  165. if (check) {
  166. checkGoPlay();
  167. }
  168. }
  169. }
  170. _onLatestDataError(error) {
  171. _log.info('_onLatestDataError.... $error');
  172. if (latest == null || latest!.isEmpty || latest!.length < 20) {
  173. // 列表数据如果少于20,说明只是内置图,仍然刷新远程请求
  174. _log.warning("_onLatestDataError, retry again");
  175. // refresh();
  176. Future.delayed(Duration(seconds: 3), () => refresh());
  177. }
  178. }
  179. Future<void> refresh() async {
  180. _log.info('refresh...');
  181. await latestCachedRequest.refresh();
  182. }
  183. // ListItem? get currentItem {
  184. // if (latest != null && latest!.isNotEmpty && data.currentLevel < latest!.length) {
  185. // // return latest![data.currentLevel]; // 原来的逻辑,太过简单,如果后台图片有调整顺序变了,用户可能会遇到重复的图
  186. // // todo... 改成从latest列表中查找首个 data.completedWorks 中不存在的图(即首个未完成图)
  187. // }
  188. // return null;
  189. // }
  190. ListItem? get currentItem {
  191. // 1. 确保 latest 数据已加载
  192. if (latest == null || latest!.isEmpty) {
  193. return null;
  194. }
  195. // 2. 获取已完成作品的唯一标识符集合,方便快速查找
  196. // 假设 ListItem 的 id/url/name 等属性是其唯一标识。
  197. // 我们使用 id 作为唯一标识符。
  198. final Set<String> completedIds = data.completedWorks.value.map((work) => work.id).toSet();
  199. // 3. 遍历 latest 列表,查找第一个未完成的 Item
  200. for (final item in latest!) {
  201. // 假设 ListItem 有一个唯一的 id 属性。
  202. // 如果 ListItem 没有 id,您需要使用其 URL 或其他唯一标识。
  203. // 这里我们假设 ListItem 是 RemoteItem/AssetItem 的基类,它们有一个 String 类型的 id 属性。
  204. final String itemId = item.id;
  205. // 检查这个 id 是否在已完成集合中
  206. if (!completedIds.contains(itemId)) {
  207. _log.info('Found current item: $itemId');
  208. return item; // 返回找到的第一个未完成的 Item
  209. }
  210. }
  211. // 4. 如果所有图片都完成了
  212. _log.info('All items in the latest list have been completed.');
  213. return null;
  214. }
  215. /// 预加载未来 N 张图片到磁盘,并最后触发当前关卡下载以最大化内存缓存命中率。
  216. void _preloadNextImages() {
  217. // 预加载数量 (包括当前关卡在内,共 20 个)
  218. const int totalPreloadCount = 20;
  219. // 1. 确保 latest 数据已加载
  220. if (latest == null || latest!.isEmpty || latest!.length < minimumRemoteLoadCount) {
  221. _log.info('Preload failed: latest list is empty.');
  222. return;
  223. }
  224. // 2. 查找当前未完成的第一张图片的索引 (Index of currentItem)
  225. final Set<String> completedIds = data.completedWorks.value.map((work) => work.id).toSet();
  226. int startIndex = -1;
  227. for (int i = 0; i < latest!.length; i++) {
  228. if (!completedIds.contains(latest![i].id)) {
  229. startIndex = i;
  230. break;
  231. }
  232. }
  233. if (startIndex == -1) {
  234. _log.info('Preload: All images completed, nothing to preload.');
  235. return;
  236. }
  237. // 确定预加载范围 (从当前图片startIndex到 totalPreloadCount 个图片)
  238. final int endPreloadIndex = min(startIndex + totalPreloadCount, latest!.length);
  239. // 3. 准备要加载的列表 (从 startIndex 开始)
  240. final List<ListItem> itemsToLoad = latest!.sublist(startIndex, endPreloadIndex);
  241. if (itemsToLoad.isEmpty) {
  242. _log.info('Preload: No items found in the range.');
  243. return;
  244. }
  245. // 4. 将当前关卡 (第一个元素) 移动到列表的末尾
  246. final ListItem currentItemToLoad = itemsToLoad.removeAt(0);
  247. itemsToLoad.add(currentItemToLoad);
  248. _log.info('Preloading ${itemsToLoad.length} images. Current item: ${currentItemToLoad.id} will be loaded last.');
  249. // 5. 循环触发 ItemLoader 加载
  250. int preloadCount = 0;
  251. for (final itemToLoad in itemsToLoad) {
  252. // 对远程图片进行预加载
  253. // 调用 ItemLoader.load,它会使用 Download 单例进行下载和缓存
  254. // 我们不关心返回值或 Future,只是触发下载
  255. if (itemToLoad is RemoteItem) {
  256. try {
  257. // 触发下载。对于非当前关卡,下载器会完成下载并写入磁盘,然后可能释放内存。
  258. // 对于当前关卡 (最后一个被调用的),它留在内存中的可能性最大。
  259. ItemLoader.load(itemToLoad);
  260. preloadCount++;
  261. } catch (e) {
  262. _log.warning('Failed to load item for preloading: ${itemToLoad.id}, error: $e');
  263. }
  264. }
  265. }
  266. _log.info('Preload initiated for $preloadCount remote images, current item was last.');
  267. }
  268. @override
  269. Widget build(BuildContext context) {
  270. if (isLoading) return scrollableDummy;
  271. // 2. 计算画布尺寸(宽=屏幕宽-60,高=宽×3/2)
  272. // final canvasWidth = device.screenSize.width - 30 * 2; // 左右各30px
  273. // final canvasHeight = canvasWidth * 3 / 2;
  274. final double availableHeight = device.screenSize.height - device.appBarHeight - device.bannerHeight - 120;
  275. final double paddedWidth = device.screenSize.width - 2 * 30; // padding width 30
  276. final double paddedHeight = availableHeight;
  277. final double targetWidth = paddedWidth;
  278. final double targetHeight = targetWidth * device.aspectRatio;
  279. final double canvasWidth;
  280. final double canvasHeight;
  281. if (targetHeight > paddedHeight) {
  282. canvasHeight = paddedHeight;
  283. canvasWidth = paddedHeight / device.aspectRatio;
  284. } else {
  285. canvasWidth = targetWidth;
  286. canvasHeight = targetHeight;
  287. }
  288. return Scaffold(
  289. appBar: AppBar(
  290. backgroundColor: Colors.white,
  291. elevation: 1,
  292. centerTitle: true,
  293. leading: RepaintBoundary(
  294. // !!! 改造点 3: 添加 ScaleTransition
  295. key: _collectionKey, // 关联 GlobalKey
  296. child: ScaleTransition(
  297. scale: _collectionAnimation, // 使用定义的放大/缩小动画
  298. child: IconButton(
  299. onPressed: () {
  300. audio.playSfx(SfxType.click);
  301. Navigator.push(context, CollectionScreen.buildRoute());
  302. },
  303. icon: const Icon(Icons.collections, color: Colors.black87),
  304. ),
  305. ),
  306. ),
  307. // title: const Text(
  308. // 'Jigsort Solitaire',
  309. // style: TextStyle(color: Colors.black87, fontWeight: FontWeight.bold, fontSize: 24),
  310. // ),
  311. // 🚀 改造点:将 Text 标题替换为 SvgPicture
  312. title: SvgPicture.asset(
  313. 'assets/images/title.svg', // 替换为您的 SVG 文件路径
  314. height: 32, // 根据您的设计调整高度,确保它在 AppBar 中显示良好
  315. // colorFilter: const ColorFilter.mode(Colors.black87, BlendMode.srcIn), // 如果SVG是单色,可以设置颜色
  316. placeholderBuilder: (BuildContext context) => const Text(
  317. // 占位符,以防SVG加载失败
  318. 'Jigsort Solitaire',
  319. style: TextStyle(color: Colors.black87, fontWeight: FontWeight.bold, fontSize: 24),
  320. ),
  321. ),
  322. actions: [
  323. IconButton(
  324. onPressed: () {
  325. audio.playSfx(SfxType.click);
  326. // Navigator.push(context, SettingsDialog.buildRoute());
  327. Navigator.push(context, SettingScreen.buildRoute());
  328. },
  329. icon: const Icon(Icons.settings, color: Colors.black87),
  330. ),
  331. ],
  332. ),
  333. body: Column(
  334. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  335. children: [
  336. Expanded(
  337. child: Column(
  338. mainAxisAlignment: MainAxisAlignment.spaceEvenly,
  339. children: [
  340. // 2. 画布区域(固定尺寸)
  341. Padding(
  342. padding: const EdgeInsets.symmetric(horizontal: 30), // 左右30px
  343. child: SizedBox(
  344. width: canvasWidth,
  345. height: canvasHeight,
  346. child: ValueListenableBuilder(
  347. valueListenable: data.completedWorks,
  348. builder: (context, value, child) {
  349. return HomeBoardPlay(
  350. key: _canvasKey,
  351. canvasWidth: canvasWidth,
  352. canvasHeight: canvasHeight,
  353. collectionKey: _collectionKey,
  354. onCollectionDone: () {
  355. // collection unlocking 动画结束,启动collection button 的接收反馈动画
  356. _log.info('onCollectionDone, 启动合集收纳反馈动画');
  357. audio.playSfx(SfxType.appear);
  358. _collectionController.forward(from: 0.0);
  359. },
  360. );
  361. },
  362. ),
  363. ),
  364. ),
  365. playButton,
  366. ],
  367. ),
  368. ),
  369. SafeArea(
  370. child: SizedBox(
  371. // 始终预留一个固定的高度,防止布局跳变
  372. height: context.read<Device>().bannerHeight,
  373. width: double.infinity,
  374. child: FutureBuilder<bool>(
  375. future: _bannerReadyAndShouldShow(),
  376. builder: (context, snapshot) {
  377. if (snapshot.hasData && snapshot.data == true) {
  378. return adBanner;
  379. }
  380. return Container(
  381. // color: Colors.grey.shade100,
  382. );
  383. },
  384. ),
  385. ),
  386. ),
  387. ],
  388. ),
  389. );
  390. }
  391. void gotoPlay(ListItem item, {bool firstRun = false}) async {
  392. _log.info('goto play, firstRun = $firstRun');
  393. // !!! 增加保护
  394. if (!mounted) return;
  395. PageRouteBuilder? pageRouteBuilder = BoardPlay.buildRoute(item, firstRun: firstRun);
  396. final result = await Navigator.push(context, pageRouteBuilder);
  397. if (!mounted) return;
  398. if (result != null && result == true) {
  399. // 通关返回, 展示翻牌
  400. _canvasKey.currentState?.startFlipAnimation();
  401. final bool hasSufficientData = latest != null && latest!.length >= minimumRemoteLoadCount;
  402. final bool isNetworkActive = latestCachedRequest.hasRecentSuccessfulFetch;
  403. if (hasSufficientData) {
  404. // 1. 数据完整:如果网络活跃,立即顺延预加载。
  405. if (isNetworkActive) {
  406. _log.info('Game finished, data complete & Network Active. Triggering sequential preloading...');
  407. _preloadNextImages();
  408. } else {
  409. // 2. 数据完整但网络不活跃/状态未知:尝试刷新,让 _onLatestDataUpdate 负责后续处理
  410. _log.info('Game finished, data complete but Network inactive. Attempting refresh.');
  411. refresh();
  412. }
  413. } else {
  414. // 3. 数据不完整:无论如何都需要刷新,让 _onLatestDataUpdate 重新处理
  415. _log.info('Game finished, remote data incomplete. Attempting refresh...');
  416. refresh();
  417. }
  418. } else {
  419. // 非关卡通关返回,在这里播放插屏广告
  420. // showInterstitialAd("level_exit", currentItem!.id, data.currentLevel);
  421. }
  422. }
  423. Widget get playButton {
  424. return MyElevatedButton(
  425. width: device.isTablet ? 300 : 200,
  426. height: 70,
  427. borderRadius: BorderRadius.circular(20),
  428. gradient: LinearGradient(colors: [SkinHelper.coreBgColor, SkinHelper.slotBorderColor]),
  429. onPressed: () async {
  430. audio.playSfx(SfxType.click);
  431. if (currentItem != null) {
  432. gotoPlay(currentItem!);
  433. } else {
  434. Fluttertoast.showToast(
  435. msg: AppLocalizations.of(context)!.noMorePicture,
  436. toastLength: Toast.LENGTH_SHORT,
  437. gravity: ToastGravity.CENTER,
  438. timeInSecForIosWeb: 1,
  439. backgroundColor: SkinHelper.slotBorderColor,
  440. textColor: Colors.white,
  441. fontSize: 16.0,
  442. );
  443. }
  444. },
  445. child: Column(
  446. mainAxisAlignment: MainAxisAlignment.center,
  447. children: [
  448. Text(
  449. AppLocalizations.of(context)!.play,
  450. style: TextStyle(color: Colors.white, fontSize: 24, fontWeight: FontWeight.bold),
  451. ),
  452. ValueListenableBuilder<List<Work>>(
  453. valueListenable: data.completedWorks,
  454. builder: (context, isSoundOn, child) {
  455. return Text('${AppLocalizations.of(context)!.level} ${data.currentLevel + 1}', style: const TextStyle(color: Colors.white, fontSize: 16));
  456. },
  457. ),
  458. ],
  459. ),
  460. );
  461. }
  462. Widget get scrollableDummy => Scaffold(
  463. body: LayoutBuilder(
  464. builder: (p0, p1) {
  465. return SingleChildScrollView(
  466. physics: const AlwaysScrollableScrollPhysics(),
  467. child: SizedBox(
  468. height: p1.maxHeight,
  469. child: Center(child: ListView(shrinkWrap: true, children: [Lottie.asset('assets/lottie/loading.json', height: 100)])),
  470. ),
  471. );
  472. },
  473. ),
  474. );
  475. ///////////////////////// 初始化相关 /////////////////////////
  476. static bool hasInit = false;
  477. static MyMethodChannel platform = MyMethodChannel();
  478. // 在列表刷出来后才正式初始化admod等组件
  479. void initThird() async {
  480. if (hasInit) return;
  481. hasInit = true;
  482. // 有了UMP后, 这里的ATT就不需要了
  483. // bool auth = await initATT();
  484. // if (auth) {
  485. // await platform.setHasUserConsent(true);
  486. // await platform.setAdvertiserTrackingEnabled(true);
  487. // }
  488. // await initUMP(); // 征询欧洲用户同意 // applovin max 已经可以自动处理,这里不需要了
  489. TrackingStatus attStatus = await AppTrackingTransparency.trackingAuthorizationStatus;
  490. if (attStatus == TrackingStatus.authorized && Platform.isIOS) {
  491. // ATT 通过之后,ios需要调用相关的原生sdk接口做进一步的初始化
  492. // await platform.setHasUserConsent(true);
  493. // await platform.setAdvertiserTrackingEnabled(true);
  494. }
  495. initFCM(); // 消息推送许可弹窗
  496. initAd(); // admod 的广告加载安排在iOS ATT 之后,以便能够加载到个性化广告
  497. AdjustHelper.init(Persistence().uuid); // 初始化Adjust
  498. final idfa = await AppTrackingTransparency.getAdvertisingIdentifier();
  499. _log.info("idfa: $idfa");
  500. }
  501. /////////////////////////// ATT ///////////////////////////
  502. // Platform messages are asynchronous, so we initialize in an async method.
  503. Future<bool> initATT() async {
  504. TrackingStatus status = await AppTrackingTransparency.trackingAuthorizationStatus;
  505. _log.info('initATT111 $status');
  506. // If the system can show an authorization request dialog
  507. if (status == TrackingStatus.notDetermined) {
  508. // Show a custom explainer dialog before the system dialog
  509. // await showCustomTrackingDialog(context);
  510. // Wait for dialog popping animation
  511. // await Future.delayed(const Duration(milliseconds: 200));
  512. // Request system's tracking authorization dialog
  513. status = await AppTrackingTransparency.requestTrackingAuthorization();
  514. _log.info('initATT222 $status');
  515. }
  516. if (status == TrackingStatus.authorized) {
  517. return true;
  518. }
  519. return false;
  520. }
  521. // no need
  522. Future<void> showCustomTrackingDialog(BuildContext context) async => await showDialog<void>(
  523. context: context,
  524. builder: (context) => AlertDialog(
  525. title: const Text('Dear User'),
  526. content: const Text(
  527. 'We care about your privacy and data security. We keep this app free by showing ads. '
  528. 'Can we continue to use your data to tailor ads for you?\n\nYou can change your choice anytime in the app settings. '
  529. 'Our partners will collect data and use a unique identifier on your device to show you ads.',
  530. ),
  531. actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('Continue'))],
  532. ),
  533. );
  534. /////////////////////////////////////////////////////////
  535. /// 初始化广告模块
  536. initAd() {
  537. _log.info('initAd');
  538. // AdsController adsController = context.read<AdsController>();
  539. // adsController.initialize();
  540. ApplovinAdsController applovinAdsController = context.read<ApplovinAdsController>();
  541. applovinAdsController.initialize();
  542. }
  543. /// gallery页面加载的时候,可能广告模块还没有初始化完毕
  544. Future<bool> _bannerReadyAndShouldShow() async {
  545. bool ready = await adSDKReady();
  546. return ready && shouldShowBannerAd(data.currentLevel);
  547. }
  548. /////////////////////////// FCM ///////////////////////////
  549. // 消息推送许可弹框
  550. initFCM() async {
  551. try {
  552. final fcmToken = await FirebaseMessaging.instance.getToken();
  553. _log.info("FCM Token: $fcmToken");
  554. FirebaseMessaging messaging = FirebaseMessaging.instance;
  555. NotificationSettings settings = await messaging.requestPermission(
  556. alert: true,
  557. announcement: false,
  558. badge: true,
  559. carPlay: false,
  560. criticalAlert: false,
  561. provisional: false,
  562. sound: true,
  563. );
  564. _log.warning('User granted permission: ${settings.authorizationStatus}');
  565. } catch (e) {
  566. FirebaseCrashlytics.instance.log("FCM FirebaseMessaging.instance.getToken error: $e");
  567. _log.warning(e);
  568. }
  569. }
  570. }