我使用了flutter后台服务插件,有时会崩溃。 我不知道为什么会这样?有什么解决办法吗?? 我尝试了很多方法..非常关键.. 我使用 flutter_background_service 1.0.4 作为后台服务和前台服务。
Fatal Exception: android.app.RemoteServiceException: Context.startForegroundService() did not
then call Service.startForeground(): ServiceRecord{67fd813 u0
com.example.sms_scheduler/id.flutter.flutter_background_service.BackgroundService}
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1797)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6651)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)
这是我的代码!!
void main() async{
await initializeService();
runApp(const MyApp());
}
Future<void> initializeService() async {
final service = FlutterBackgroundService();
await service.configure(
androidConfiguration: AndroidConfiguration(
onStart: onStart,
autoStart: true,
isForegroundMode: true,
),
iosConfiguration: IosConfiguration(
autoStart: true,
onForeground: onStart,
onBackground: onIosBackground,
),
);
}
void onIosBackground() {
WidgetsFlutterBinding.ensureInitialized();
print('FLUTTER BACKGROUND FETCH');
}
void onStart() {
if (Platform.isAndroid){PathProviderAndroid.registerWith();}
else if (Platform.isIOS){PathProviderIOS.registerWith();}
if (Platform.isIOS) FlutterBackgroundServiceIOS.registerWith();
if (Platform.isAndroid) FlutterBackgroundServiceAndroid.registerWith();
final service = FlutterBackgroundService();
service.onDataReceived.listen((event) {
if (event!["action"] == "setAsForeground") {
service.setAsForegroundService();
return;
}
if (event["action"] == "setAsBackground") {
service.setAsBackgroundService();
}
if (event["action"] == "stopService") {
service.stopService();
}
});
service.setAsBackgroundService();
Timer.periodic(const Duration(seconds: 05), (timer) async {
service.sendData(
{
"final_sms": sendFinalSMS(),
}
);
});
}
你为什么不用这个
尝试{
//可能抛出异常的代码
}catch(Exception_class_Name ref){}
同样的错误,有解决办法吗?