首页 > 解决方案 > Flutter - 退出应用程序时释放后台服务

问题描述

我构建了一个应用程序,即使应用程序关闭,它也能跟踪用户的位置。但我希望它被销毁,当用户通过 Android 中的应用程序退出终止应用程序时。目前,即使我通过真实设备的任务管理器关闭了该应用程序,我仍然会收到该应用程序在后台使用的通知。

在此处输入图像描述

这是在任务管理器中杀死应用后弹出的消息,告诉应用程序仍在后台运行。

我正在使用geofence_service包中的 WillStartForegroundTask。

这是我的代码:

class CityDetailsScreen extends StatefulWidget {
  CityDetailsScreen();

  @override
  _CityDetailsScreenState createState() => _CityDetailsScreenState();
}

class _CityDetailsScreenState extends State<CityDetailsScreen> {
  bool permissionGranted = false;

  final geofenceService = GeofenceService.instance.setup(
     interval: 5000,
     accuracy: 100,
     loiteringDelayMs: 60000,
     statusChangeDelayMs: 10000,
     useActivityRecognition: false,
     allowMockLocations: true,
     geofenceRadiusSortType: GeofenceRadiusSortType.DESC);

 @override
 Widget build(BuildContext context) {
    return WillStartForegroundTask(
      onWillStart: () {
        // You can add a foreground task start condition.
        return geofenceService.isRunningService;
      },
      androidNotificationOptions: AndroidNotificationOptions(
        channelId: 'geofence_service_notification_channel',
        channelName: 'Geofence Service Notification',
        channelDescription:
            'This notification appears when the geofence service is running in the 
              background.',
        channelImportance: NotificationChannelImportance.HIGH,
        priority: NotificationPriority.HIGH),
        iosNotificationOptions: IOSNotificationOptions(),
        notificationTitle: 'Aschaffenburger Geheimnisse läuft im Hintergrund',
        notificationText: 'Klicke, um in die App zurückzukehren!',

           child: AnnotatedRegion<SystemUiOverlayStyle>(
                    value: SystemUiOverlayStyle.light,
                  child: Scaffold(
                            body: Container()
                         )
                     )
                  );
 }

 @override
   void dispose() {
   print("DISPOSE GeofenceService");
   GeofenceService.instance.stop();
   super.dispose();
 }
}

当我分离应用程序时,服务应该被完全破坏!

有任何想法吗?

标签: flutterdartandroid-lifecycledispose

解决方案


推荐阅读