In Flutter, why does my background service stop when a call comes

585 views Asked by At

I have implemented flutter_background_service to work with foreground and background tasks at flutter side.

In Android 13 device I start background service and remove app from background while service is working properly. But when the call comes and is received the service stops.

@pragma('vm:entry-point')
void onStart() {
  WidgetsFlutterBinding.ensureInitialized();

  // For flutter prior to version 3.0.0
  GeolocatorAndroid.registerWith();
  if (Platform.isIOS) FlutterBackgroundServiceIOS.registerWith();
  if (Platform.isAndroid) FlutterBackgroundServiceAndroid.registerWith();
  // We have to register the plugin manually

  final service = FlutterBackgroundService();
  Timer? timerLocation,timerApi;

  service.onDataReceived.listen((event) {
    if (event!["action"] == "setAsForeground") {
      service.setAsForegroundService();
      return;
    }

    if (event["action"] == "setAsBackground") {
      service.setAsBackgroundService();
    }

    if (event["action"] == "stopService") {
      // print("Stop Service!!!:${event['action']}");
      service.stopService();
      timerApi!.cancel();
      timerLocation!.cancel();
    }
  });


  // bring to foreground
  if(Platform.isAndroid){
    service.setAsForegroundService();
  }

  MyApplication.getToString(key: Constant.keyLocationInterval).then((value) {
    // log('Location interval in second: ${int.parse(value)}');

    if(value.isNotEmpty){
      timerLocation = Timer.periodic(Duration(seconds: int.parse(value)), (timer) async {
        service.setNotificationInfo(
          title: "Route Start",
          content: "Initializing ${DateFormat('dd-MM-yyyy HH:mm:ss').format(DateTime.now())}",
        );
        await MyApplication.storeLocationDataIntoDB();
      },);
    }
  });

  MyApplication.getToString(key: Constant.keyApiCallInterval).then((value) {
    log('Api call interval in minute: ${int.parse(value)}');
    if(value.isNotEmpty){
      timerApi = Timer.periodic(Duration(minutes: int.parse(value)), (timer) async {
        // print('Api call in BACKGROUND: ${DateTime.now()} = ${int.parse(Constant.settingSyncInterval)}');
        await MyApplication.callLocationTracking();
      },);
    }
  });
}
0

There are 0 answers