Baseflow / flutter-geolocator

Android and iOS Geolocation plugin for Flutter
https://baseflow.com/
MIT License
1.24k stars 648 forks source link

Geolocator position updates stopped #1252

Open 10terabyte opened 1 year ago

10terabyte commented 1 year ago

I am using this package to get location update stream. Everything is good when app is active. I am using this pacakge with flutter_background_service to send location update event even app is closed.

  @pragma('vm:entry-point')
    void onStart(ServiceInstance service) async {
      await PreferencesManager.init();
      const LocationSettings locationSettings = LocationSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 10,
      );
      StreamSubscription<Position> positionStream = Geolocator.getPositionStream(locationSettings: locationSettings).listen(
          (Position? position) {
            print("Location Tracking");
            LocationApi locationApi = LocationApi();
            locationApi.sendLocation(position?.latitude, position?.longitude);
            print(position == null ? 'Unknown' : '${position.latitude.toString()}, ${position.longitude.toString()}');
      });
      DartPluginRegistrant.ensureInitialized();

      if (service is AndroidServiceInstance) {
        service.on('setAsForeground').listen((event) {
          service.setAsForegroundService();
        });

        service.on('setAsBackground').listen((event) {
          service.setAsBackgroundService();
        });
      }

      service.on('stopService').listen((event) {
        service.stopSelf();
      });
    }

But when I close app, I get this log.

FlutterGeolocator       com.example.flutter_background_location_service                 D  Detaching Geolocator from activity
FlutterGeolocator       com.example.flutter_background_location_service                 D  Flutter engine disconnected. Connected engine count 2
FlutterGeolocator       com.example.flutter_background_location_service                 D  Disposing Geolocator services
FlutterGeolocator       com.example.flutter_background_location_service                 E  Geolocator position updates stopped
FlutterGeolocator       com.example.flutter_background_location_service                 E  There is still another flutter engine connected, not stopping location service

Any solution for this?

fesp commented 1 year ago

I (more or less) have the same issue, although I'm not using flutter_background_service but flutter_foreground_task.. When starting up the app (and checking for the required permissions using the methods provided by the library) I see this:

Attaching Geolocator to activity
Creating service.
Binding to location service.
Geolocator foreground service connected
Initializing Geolocator services
Flutter engine connected. Connected engine count 1

Then, after the new isolate for the foreground service is started in which the app listens for position updates this is shown:

Geolocator foreground service connected
Initializing Geolocator services
Flutter engine connected. Connected engine count 2
Geolocator position updates started

So far, so good. At this point I'm receiving position updates as expected. But then, when I close the app I stop receiving those updates:

Detaching Geolocator from activity
Flutter engine disconnected. Connected engine count 1
Disposing Geolocator services
Geolocator position updates stopped
There is still another flutter engine connected, not stopping location service

By looking at the logs it seems the reference counting works fine, but despite that Geolocator stops sending updates.

TimHoogstrate commented 1 year ago

In order to help us investigating the issue, could you please post the output of flutter doctor -v and I suspect that you found this issue while testing on Android, is that correct?

fesp commented 1 year ago

Ah, yes, the issue is on Android. Here is the output of flutter doctor -v:

[✓] Flutter (Channel stable, 3.10.5, on macOS 13.4 22F66 darwin-arm64, locale en-GB) • Flutter version 3.10.5 on channel stable at /Users/fesp/Library/flutter • Upstream repository https://github.com/flutter/flutter.git • Framework revision 796c8ef792 (8 days ago), 2023-06-13 15:51:02 -0700 • Engine revision 45f6e00911 • Dart version 3.0.5 • DevTools version 2.23.1

[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0) • Android SDK at /Users/fesp/Library/Android/sdk • Platform android-33, build-tools 31.0.0 • ANDROID_HOME = /Users/fesp/Library/Android/sdk • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 11.0.15+0-b2043.56-8887301) • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.3) • Xcode at /Applications/Xcode.app/Contents/Developer • Build 14E222b • CocoaPods version 1.11.2

[✓] Chrome - develop for the web • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2022.1) • Android Studio at /Applications/Android Studio.app/Contents • Flutter plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/6351-dart • Java version OpenJDK Runtime Environment (build 11.0.15+0-b2043.56-8887301)

[✓] IntelliJ IDEA Community Edition (version 2021.3.2) • IntelliJ at /Applications/IntelliJ IDEA CE.app • Flutter plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code (version 1.79.2) • VS Code at /Applications/Visual Studio Code.app/Contents • Flutter extension version 3.12.2

[✓] Connected device (2 available) • macOS (desktop) • macos • darwin-arm64 • macOS 13.4 22F66 darwin-arm64 • Chrome (web) • chrome • web-javascript • Google Chrome 114.0.5735.133

[✓] Network resources • All expected network resources are available.

• No issues found!

anh-ht commented 1 year ago

same issues :(

github-actions[bot] commented 1 year ago

Without additional information, we are unfortunately not able to resolve this issue. Therefore, we reluctantly closed this issue for now. If you run into this issue later, feel free to file a new issue with a reference to this issue. Add a description of detailed steps to reproduce, expected and current behaviour, logs and the output of 'flutter doctor -v'. Thanks for your contribution.

root4417 commented 1 year ago

Use TaskQueues. 2023-09-26 01:07:16.607 12319-12319 FlutterGeolocator io.hexasoft.ceert_audit D Geolocator foreground service connected 2023-09-26 01:07:16.607 12319-12319 FlutterGeolocator io.hexasoft.ceert_audit D Initializing Geolocator services 2023-09-26 01:07:16.607 12319-12319 FlutterGeolocator io.hexasoft.ceert_audit D Flutter engine connected. Connected engine count 2 2023-09-26 01:07:16.607 12319-12468 FlutterJNI io.hexasoft.ceert_audit W FlutterJNI.loadLibrary called more than once 2023-09-26 01:07:16.608 12319-12359 ResourceExtractor io.hexasoft.ceert_audit I Found extracted resources res_timestamp-22-1695672416033 2023-09-26 01:07:16.608 12319-12358 FlutterJNI io.hexasoft.ceert_audit W FlutterJNI.prefetchDefaultFontManager called more than once 2023-09-26 01:07:16.610 12319-12319 FlutterJNI io.hexasoft.ceert_audit W FlutterJNI.init called more than once 2023-09-26 01:07:18.138 12319-12481 flutter io.hexasoft.ceert_audit I task: backgroundUploadTask 2023-09-26 01:07:18.139 12319-12481 flutter io.hexasoft.ceert_audit I inputData: {backgroundTask: one off} 2023-09-26 01:07:18.142 12319-12481 flutter io.hexasoft.ceert_audit I Scheduled task executed! 2023-09-26 01:07:22.144 12319-12319 FileSaver io.hexasoft.ceert_audit D Detached From Engine 2023-09-26 01:07:22.145 12319-12319 FlutterGeolocator io.hexasoft.ceert_audit D Flutter engine disconnected. Connected engine count 1 2023-09-26 01:07:22.150 12319-12406 WM-WorkerWrapper io.hexasoft.ceert_audit I Worker result SUCCESS for Work [ id=5a80a0e9-9a16-47db-bf76-ceea1ca95461, tags={ be.tramckrijte.workmanager.BackgroundWorker } ] 2023-09-26 01:07:22.153 12319-12319 FlutterGeolocator io.hexasoft.ceert_audit D Disposing Geolocator services 2023-09-26 01:07:22.153 12319-12319 FlutterGeolocator io.hexasoft.ceert_audit E Geolocator position updates stopped 2023-09-26 01:07:22.153 12319-12319 FlutterGeolocator io.hexasoft.ceert_audit E There is still another flutter engine connected, not stopping location service

root4417 commented 1 year ago

[✓] Flutter (Channel stable, 3.10.6, on macOS 13.5.2 22G91 darwin-x64, locale en-PK) • Flutter version 3.10.6 on channel stable at /Users/muhammad/flutter3.10.6 • Upstream repository https://github.com/flutter/flutter.git • Framework revision f468f3366c (3 months ago), 2023-07-12 15:19:05 -0700 • Engine revision cdbeda788a • Dart version 3.0.6 • DevTools version 2.23.1

saurabhkumar8112 commented 9 months ago

This happened with me as well when i switched off the internet

Wackymax commented 9 months ago

Also running into this now. Seems to be a regression that was introduced at some point. I originally made the PR to do the reference counting and will have a look at this and fix it again. It might be that someone tried to address this issue https://github.com/Baseflow/flutter-geolocator/issues/1395 so we might need a new flag to do reference counting on Android. In my opinion though people should be closing the stream manually when their application is stopped or moved to the background. Any thoughts on how to approach this @mvanbeusekom ?

fesp commented 9 months ago

Manually closing the stream when needed sounds like a great option.

fesp commented 7 months ago

Also running into this now. Seems to be a regression that was introduced at some point. I originally made the PR to do the reference counting and will have a look at this and fix it again. It might be that someone tried to address this issue #1395 so we might need a new flag to do reference counting on Android. In my opinion though people should be closing the stream manually when their application is stopped or moved to the background. Any thoughts on how to approach this @mvanbeusekom ?

@Wackymax Did you already find some time to have a look at this?

Wackymax commented 7 months ago

Not yet noOn 10 Feb 2024, at 17:21, Ferry @.***> wrote:

Also running into this now. Seems to be a regression that was introduced at some point. I originally made the PR to do the reference counting and will have a look at this and fix it again. It might be that someone tried to address this issue #1395 so we might need a new flag to do reference counting on Android. In my opinion though people should be closing the stream manually when their application is stopped or moved to the background. Any thoughts on how to approach this @mvanbeusekom ?

@Wackymax Did you already find some time to have a look at this?

—Reply to this email directly, view it on GitHub, or unsubscribe.You are receiving this because you were mentioned.Message ID: @.***>

saurabhkumar8112 commented 7 months ago

I am facing this as well. The way I could reproduce this is, keep my app offline for a while and then try building in debug mode again(while internet is OFF).

Though i don't see why geolocator plugin should be remotely related to internet availability.

bonnerwork commented 6 months ago

I have same issue with this.

mvanbeusekom commented 6 months ago

Hi @Wackymax,

Unfortunately I don't have a lot of experience with running tasks in the background. However I have been reading up on it and I am wondering if it would not make more sense to give more control to the application developer and let the developer explicitly start / stop the foreground service when the app detects that it is moved in or out of the background? The application can then start a new (separate) stream that specifically focusses on handling location updates the occur in the background.

I have the feeling that (especially on Android) this would remove some of the complexity around the reference counting and sharing the same stream.

How do you feel about this?

DISCLAIMER: as mentioned I don't have experience with Android foreground / background services, so I might be missing some really important aspects here.

Wackymax commented 6 months ago

That is definitely possible. In fact that is what I am doing in my app. Starting the foreground service means in my mind that the intent of the developer is to start a background service for Geolocator, making the reference counting necessary. If the developer just wants the location stream to stay alive while the app activity is alive then don’t pass in the foreground notification config. That will then not start a background service that does reference counting. The only point for passing the foreground config is to try and keep the activity alive a bit longer by raising it’s priority.

If the app developers do want to have a background service that runs even when the app activity is killed then they should use a background service flutter package and start the geolocator in that package.

This entire thread is confusing me a little because it seems like the expectation is that the location service should stop when the activity is destroyed, but that is already the default behaviour when there is no foreground notification passed in. Unless I am misunderstanding something.

On 20 Mar 2024, at 11:37, Maurits van Beusekom @.***> wrote:

Hi @Wackymax https://github.com/Wackymax,

Unfortunately I don't have a lot of experience with running tasks in the background. However I have been reading up on it and I am wondering if it would not make more sense to give more control to the application developer and let the developer explicitly start / stop the foreground service when the app detects that it is moved in or out of the background? The application can then start a new (separate) stream that specifically focusses on handling location updates the occur in the background.

I have the feeling that (especially on Android) this would remove some of the complexity around the reference counting and sharing the same stream.

How do you feel about this?

DISCLAIMER: as mentioned I don't have experience with Android foreground / background services, so I might be missing some really important aspects here.

— Reply to this email directly, view it on GitHub https://github.com/Baseflow/flutter-geolocator/issues/1252#issuecomment-2009130611, or unsubscribe https://github.com/notifications/unsubscribe-auth/ACYF27MYNT42RT3BQ2ATPX3YZFKG5AVCNFSM6AAAAAAXWCAKC6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDAMBZGEZTANRRGE. You are receiving this because you were mentioned.

fesp commented 6 months ago

@Wackymax In my situation it is like this. I want to have a “service” that keeps on running even when the Android activity is killed. This service should get the data from the GPS, and get some data from a BLE sensor. For this I’m using the following packages:

flutter_background_service: ^5.0.5 geolocator: ^10.1.0 flutter_blue_plus: 1.31.12

With flutter_background_service I start a new isolate and do everything I need from there. So within that isolate I’m using geolocator and flutter_blue_plus. That works just fine. However whenever I kill the app/activity I see this:

D/SessionLifecycleClient(13736): Sending lifecycle 2 to service D/SessionLifecycleService(13736): Activity backgrounding at 629943097 D/FlutterGeolocator(13736): Detaching Geolocator from activity D/FBP-Android: [FBP] onDetachedFromActivity D/FlutterGeolocator(13736): Flutter engine disconnected. Connected engine count 1 D/FlutterGeolocator(13736): Disposing Geolocator services E/FlutterGeolocator(13736): Geolocator position updates stopped E/FlutterGeolocator(13736): There is still another flutter engine connected, not stopping location service

The BLE stuff keeps on running, but the location updates stop. Probably because geolocator is tied to the activity, and the BLE stuff isn’t.

Note that I can’t use the foreground notification of geolocator as I already have such a notification from flutter_background_service.

I’m more than happy to help out with this issue, but I’d like some guidance from you on how to approach this. I’m sure I’m not the only one who would like to use geolocator in the way that I do.

Wackymax commented 6 months ago

If that's the case I'll take a look. I am using Geolocator in the same manner. On 21 Mar 2024, at 13:19, Fesp @.***> wrote: @Wackymax In my situation it is like this. I want to have a “service” that keeps on running even when the Android activity is killed. This service should get the data from the GPS, and get some data from a BLE sensor. For this I’m using the following packages: flutter_background_service: ^5.0.5 geolocator: ^10.1.0 flutter_blue_plus: 1.31.12 With flutter_background_service I start a new isolate and do everything I need from there. So within that isolate I’m using geolocator and flutter_blue_plus. That works just fine. However whenever I kill the app/activity I see this: D/SessionLifecycleClient(13736): Sending lifecycle 2 to service D/SessionLifecycleService(13736): Activity backgrounding at 629943097 D/FlutterGeolocator(13736): Detaching Geolocator from activity D/FBP-Android: [FBP] onDetachedFromActivity D/FlutterGeolocator(13736): Flutter engine disconnected. Connected engine count 1 D/FlutterGeolocator(13736): Disposing Geolocator services E/FlutterGeolocator(13736): Geolocator position updates stopped E/FlutterGeolocator(13736): There is still another flutter engine connected, not stopping location service The BLE stuff keeps on running, but the location updates stop. Probably because geolocator is tied to the activity, and the BLE stuff isn’t. Note that I can’t use the foreground notification of geolocator as I already have such a notification from flutter_background_service. I’m more than happy to help out with this issue, but I’d like some guidance from you on how to approach this. I’m sure I’m not the only one who would like to use geolocator in the way that I do.

—Reply to this email directly, view it on GitHub, or unsubscribe.You are receiving this because you were mentioned.Message ID: @.***>

mvanbeusekom commented 6 months ago

@Wackymax, I have spend some more time looking into how to keep the location services running in the background and I am starting to understand the concept of Foreground services in Android.

I also think I understand the concept you implemented regarding the flutter engine reference counting, as this probably comes into play when using the flutter_background_service plugin (or something similar).

Am I correct to assume that the current working procedure would be to:

  1. Start the Geolocator.getPositionStream when the app is active (increases the connectedEngines to 1).
  2. Register a callback with the flutter_background_service plugin to listen to the Geolocator.getPositionStream (increasing the connectedEngines to 2).
  3. Force closing the application causes the onDetachedFromEngine to be called, decreasing the connectedEngine back to 1)
  4. The flutter_background_service keeps an Dart isolate running listening to the position stream even when the application is "force" closed.

The way I understand the current implementation is that the Android Foreground service (GeolocatorLocationService) will keep the native part active. However to keep receiving location updates on the Dart side something extra is needed, like the flutter_background_service or a custom implementation keeping an isolate running and listening to the location stream.

Wackymax commented 6 months ago

@Wackymax, I have spend some more time looking into how to keep the location services running in the background and I am starting to understand the concept of Foreground services in Android.

I also think I understand the concept you implemented regarding the flutter engine reference counting, as this probably comes into play when using the flutter_background_service plugin (or something similar).

Am I correct to assume that the current working procedure would be to:

  1. Start the Geolocator.getPositionStream when the app is active (increases the connectedEngines to 1).
  2. Register a callback with the flutter_background_service plugin to listen to the Geolocator.getPositionStream (increasing the connectedEngines to 2).
  3. Force closing the application causes the onDetachedFromEngine to be called, decreasing the connectedEngine back to 1)
  4. The flutter_background_service keeps an Dart isolate running listening to the position stream even when the application is "force" closed.

The way I understand the current implementation is that the Android Foreground service (GeolocatorLocationService) will keep the native part active. However to keep receiving location updates on the Dart side something extra is needed, like the flutter_background_service or a custom implementation keeping an isolate running and listening to the location stream.

The way I have it in my app that seems to work correctly is to only do Step 2. You are correct in that the native part will stay active but you need something to handle the dart side correctly.

One thing I have noticed is that my connected engine count is 4 when the activity is closed so I have a lot more happening in my app that is maybe keeping the location updates alive.

I am a bit busy on my project now to reach some deadlines but I can help to review a PR if someone creates one? I think the correctly solution would probably be to keep track of the engine id's for the engines that need location updates and check that before deciding to stop location updates. It will also help to solve https://github.com/Baseflow/flutter-geolocator/issues/1395

qky1412 commented 6 months ago

I am facing this as well. The way I could reproduce this is, keep my app offline for a while and then try building in debug mode again(while internet is OFF).

Though i don't see why geolocator plugin should be remotely related to internet availability.

Hello~Any further updates about this? Me aswell face the situdation that when app is losing network data for a while, entire "position updates" will stop. @saurabhkumar8112

Wackymax commented 5 months ago

We don't use anything related to the netword for position data so I'm not sure why that might be happening. Maybe it's something related to Android and power saving switching off the location updates after a while?

daviddagan commented 5 months ago

when i change battery optimization to unrestricted the location in the background works just fine. as I understand so far, location in the background has to be dependent only by "location always permission" so I am not so sure why unrestricted my app battery helps solve this