ekasetiawans / flutter_background_service

251 stars 165 forks source link

Stop Service on App kill (Android) #420

Open JagritAndroidDev opened 2 months ago

JagritAndroidDev commented 2 months ago

Hi team I'm facing an issue that I'm not able to stop the service whenever the application is forcely killed by the user. (I mean the user has strike off the application from the app recents). Current Code: service.on(BackgroundCommands.destroy).listen((event) async { await disconnectDevice(service); await deleteDevice(); await service.stopSelf(); });

This is my current code, but it's not working as expected. I've two doubts:

  1. Should I add the following code as well? If so, how will it help await flutterLocalNotificationsPlugin .resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>() ?.stopForegroundService();

  2. Do I need to change some code at the Android Native level to make that work? I saw some code snippets related onTaskRemoved but it doesn't work at all.

Kindly share your views to achieve this functionality

HassanButt2019 commented 2 months ago

How are you able to execute background service when app is killed by the user ?

JagritAndroidDev commented 2 months ago

@HassanButt2019 since this is the service, so it will anyway keep running in Background ` static Future initializeService( FlutterBackgroundService service) async { flutterLocalNotificationsPlugin = await NotificationUtils.setUp(); await NotificationUtils.setUpBackgroundService( flutterLocalNotificationsPlugin: flutterLocalNotificationsPlugin, channelId: BleServiceNotificationConstants.bleServiceNotificationChannelId, channelName: BleServiceNotificationConstants.bleServiceNotificationChannelName, description: 'bleService.ble_service_notification_description'.tr(), );

await service.configure(
  androidConfiguration: AndroidConfiguration(
    // this will be executed when app is in foreground or background in separated isolate
    onStart: onStart,
    // auto start service
    autoStart: false,
    isForegroundMode: false,
    notificationChannelId:
        BleServiceNotificationConstants.bleServiceNotificationChannelId,
    initialNotificationTitle:
        BleServiceNotificationConstants.bleServiceNotificationChannelName,
    initialNotificationContent: 'Initializing',
    foregroundServiceNotificationId:
        BleServiceNotificationConstants.bleServiceNotificationId,
  ),
  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,
  ),
);

}`

euphranos commented 21 hours ago

Same issue. I tried tracking app life cycle for fix it . Therefore, i tried kill the foreground / background service with if app detached (killed) but it did not work too .