Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Run geolocations on ActivityChanged event when app is already killed. #150

Closed
usmanzaheer1995 opened this issue Nov 20, 2019 · 3 comments
Closed

Comments

@usmanzaheer1995
Copy link

Your Environment

  • Plugin version: 1.3.2
  • Platform: Android
  • OS version: Android 9
  • Device manufacturer / model: Xiaomi Mi A1
  • Flutter info (flutter doctor):
    [√] Flutter (Channel stable, v1.9.1+hotfix.5, on Microsoft Windows [Version 10.0.18362.418], locale en-US)
    [√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    [√] Android Studio (version 3.5)
    [√] VS Code (version 1.39.2)
  • Plugin config:
Future<Null> _initPlatformState() async {
    bg.BackgroundGeolocation.onActivityChange(_onActivityChange);

    bg.BackgroundGeolocation.ready(
      bg.Config(
        locationAuthorizationRequest: "Always",
        reset: false,
        debug: true,
        logLevel: bg.Config.LOG_LEVEL_VERBOSE,
        desiredAccuracy: bg.Config.DESIRED_ACCURACY_LOWEST,
        distanceFilter: 1000.0,
        stopOnTerminate: false,
        enableHeadless: true,
        startOnBoot: true,
        stopTimeout: 1,
        autoSync: false,
        foregroundService: true,
      ),
    ).then((bg.State state) {
      print('[ready] ${state.toMap()}');
      if (state.schedule.isNotEmpty) {
        bg.BackgroundGeolocation.startSchedule();
      }
    }).catchError((error) {
      print('[ready] ERROR: $error');
    });
  }

Expected Behavior

Save location to firebase using the provided url to cloud function on ActivityChange event when app is already killed.

Context

I was following this issue but it didn't solve it for me.

Basically i want to log data to server only on activity change. I have the following code:

Future<Null> _initPlatformState() async {
    bg.BackgroundGeolocation.onActivityChange(_onActivityChange);

    bg.BackgroundGeolocation.ready(
      bg.Config(
        locationAuthorizationRequest: "Always",
        reset: false,
        debug: true,
        logLevel: bg.Config.LOG_LEVEL_VERBOSE,
        desiredAccuracy: bg.Config.DESIRED_ACCURACY_LOWEST,
        distanceFilter: 1000.0,
        stopOnTerminate: false,
        enableHeadless: true,
        startOnBoot: true,
        stopTimeout: 1,
        autoSync: false,
        foregroundService: true,
      ),
    ).then((bg.State state) {
      print('[ready] ${state.toMap()}');
      if (state.schedule.isNotEmpty) {
        bg.BackgroundGeolocation.startSchedule();
      }
    }).catchError((error) {
      print('[ready] ERROR: $error');
    });
  }

  Future<void> _logToServer(Map<String, dynamic> data) async {
    Dio()
        .post(
     // the url to the cloud firebase function
      FlavorConfig.instance.values.locationUrl,
      data: data,
    )
        .then((Response response) {
      print('[data posted on ${DateTime.now()}] ${response.statusCode}');
    }).catchError((e) {
      print(e);
    });
  }

  void _onActivityChange(bg.ActivityChangeEvent event) async {
    print('[${bg.Event.ACTIVITYCHANGE}] - $event');

    if (_activity != event.activity) {
      _activity = event.activity;

      bg.BackgroundGeolocation.getCurrentPosition(
        persist: false, // <-- do not persist this location
        desiredAccuracy: 40, // <-- desire an accuracy of 40 meters or less
        maximumAge: 10000, // <-- Up to 10s old is fine.
        timeout: 30, // <-- wait 30s before giving up.
        samples: 1, // <-- sample just 1 location
      ).then((bg.Location location) async {
        Map<String, dynamic> data = {
          "activity": event.activity,
          "timestamp": location.timestamp,
          "userId": _userId,
          "userEmail": _userEmail,
          "longitude": location.coords.longitude,
          "latitude": location.coords.latitude,
          "uuid": location.uuid,
        };
        await _logToServer(data);
      }).catchError((error) {
        print("Error while fetching location: $error");
      });
    }
  }

It works fine as long as app is not killed, and when app is killed the debug sounds are played but the function is not executed. Nothing is printed in the logs on firebase. A headless task isn't working when i call the method in it.

I'm hoping you can point me in the right direction.

@christocracy
Copy link
Member

Your Flutter app no longer exists when the app is terminated. See Android Headless Mode

@usmanzaheer1995
Copy link
Author

Thank you, do you have any pointers on how to go about this in a flutter app?

@christocracy
Copy link
Member

do you have any pointers on how to go about this in a flutter app?

What do you think that link I posted above is? See Wiki Android Headless Mode.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants