import 'dart:async'; import 'dart:ui'; import 'package:call_log/call_log.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:telephony/telephony.dart'; Future initializeService() async { SharedPreferences.getInstance(); final service = FlutterBackgroundService(); await service.configure( iosConfiguration: IosConfiguration( // auto start service autoStart: true, // this will be executed when app is in foreground in separated isolate onForeground: onStart, // you have to enable background fetch capability on xcode project onBackground: onIosBackground, ), androidConfiguration: AndroidConfiguration( // this will be executed when app is in foreground or background in separated isolate onStart: onStart, // auto start service autoStart: true, isForegroundMode: true, ), ); service.startService(); } bool onIosBackground(ServiceInstance service) { WidgetsFlutterBinding.ensureInitialized(); print('FLUTTER BACKGROUND FETCH'); return true; } void onStart(ServiceInstance service) async { DartPluginRegistrant.ensureInitialized(); service.on("stopService").listen((event) { service.stopSelf(); }); //定义 int flag = 0; String? phoneNum = ""; String callState; Timer.periodic(const Duration(seconds: 1), (timer) async { //数据储存读取 final SharedPreferences prefs = await SharedPreferences.getInstance(); //获取来电状态 CallState state = await Telephony.instance.callState; callState = state.name; //发送内容信息 String content = prefs.getString("refSms")!; //发送信息的状态 int? numberSet = prefs.getInt("numIndex") ?? 0; print("号码设置$numberSet 发送内容$content"); if (callState == "IDLE") { if (flag != 0) { final Iterable entry = await CallLog.query(); phoneNum = entry.first.number; // print(phoneNum); switch (numberSet) { case 0: print("所有都发"); // Telephony.backgroundInstance // .sendSms(to: phoneNum!, message: content); flag = 0; break; case 1: if (flag > 0) { print("来电拒接"); // print("来电拒接/未接"); // print("${phoneNum!}:${ref!}"); // Telephony.backgroundInstance // .sendSms(to: phoneNum!, message: content); // print("发送成功"); } else if (flag == -1) { print("来电接听"); // print("来电接听"); // print("${phoneNum!}:$content"); // Telephony.backgroundInstance // .sendSms(to: phoneNum!, message: content); } flag = 0; break; case 2: if (entry.first.duration! > 0) { print("去电接听"); // print("${phoneNum!}:$content"); // Telephony.backgroundInstance // .sendSms(to: phoneNum!, message: content); } else { print("去电挂断"); // print("${phoneNum!}:$content"); // Telephony.backgroundInstance // .sendSms(to: phoneNum!, message: content); } flag = 0; break; } } } else if (callState == "RINGING") { flag = 1; print("打印"); } else if (callState == "OFFHOOK") { if (flag > 0) flag *= -1; if (flag == 0) flag = -2; print("打印"); } }); }