import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; import '../../services/Storage.dart'; import '../../components/commonFun.dart'; import '../../components/dioFun.dart'; int remindCount = 0; void onStart() { WidgetsFlutterBinding.ensureInitialized(); final service = FlutterBackgroundService(); service.onDataReceived.listen((event) { if (event["action"] == "setAsForeground") { service.setForegroundMode(true); return; } if (event["action"] == "setAsBackground") { service.setForegroundMode(false); } if (event["action"] == "stopService") { service.stopBackgroundService(); } }); // service.setForegroundMode(true); setRemindTimer(service); } // 设置定时提醒 setRemindTimer(FlutterBackgroundService service) async { g_remindGap = await Storage.getInt('nRemindGap'); g_remindGap = (null == g_remindGap) ? 60 : g_remindGap; // 提醒间隔默认为60S print('g_remindGap = $g_remindGap'); g_bVoiceRemind = await Storage.getBool('bVoiceRemind'); g_bVoiceRemind = (null == g_bVoiceRemind) ? true : g_bVoiceRemind; // 默认开启 print('g_bVoiceRemind = $g_bVoiceRemind'); service.setForegroundMode(g_bVoiceRemind); // 设置新的定时任务 if (g_bVoiceRemind && g_remindGap > 0) { remindCount = 0; // 循环执行定时任务,间隔 remindGap 秒 Timer.periodic(Duration(seconds: g_remindGap), (timer) async { if (await service.isServiceRunning()) { doRemind(); } else { timer.cancel(); } service.setNotificationInfo( title: "My App Service", content: "Updated at ${DateTime.now()}", ); service.sendData({"current_date": DateTime.now().toIso8601String()}); }); if (qx_code < 0) { qx_code = await Storage.getInt('qx_code'); // 在前台服务中获取,保存到用户配置中的 qx_code } print("设置间隔 ${g_remindGap}S 的定时任务成功!"); } } doRemind() async { await getReviewedList(); //注意:访问区县后台接口,需要统一添加区县代码参数 if (listReviewed.length > 0) { // 定时任务,获取待审核黑烟车记录 myPlayVoiceRemind(); remindCount++; DateTime dateTime = DateTime.now(); print( "语音提醒(gap=${g_remindGap}S) ${remindCount.toString().padLeft(6, '0')}:${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}:${dateTime.second.toString().padLeft(2, '0')}"); } }