home_screen.dart 24 KB

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