Giter Club home page Giter Club logo

Comments (8)

christocracy avatar christocracy commented on August 26, 2024 2

Next beta arriving soon.

from flutter_background_geolocation.

christocracy avatar christocracy commented on August 26, 2024

Show me where you’re listening to #onLocation, #onGeofence relative to where you’re executing #ready.

from flutter_background_geolocation.

joserocha3 avatar joserocha3 commented on August 26, 2024

My #startTracking is called on application start.

import 'package:background_fetch/background_fetch.dart';
import 'package:flutter/material.dart';
import 'package:flutter_background_geolocation/flutter_background_geolocation.dart'
    as bg;

import 'package:pointbee/utilities/notifications.dart';
import 'package:pointbee/state/app_state.dart';

/// Receive events from BackgroundGeolocation in Headless state
void backgroundGeolocationHeadlessTask(bg.HeadlessEvent headlessEvent) async {
  print('📬 --> $headlessEvent');

  await setupNotifications();

  switch (headlessEvent.name) {
    case bg.Event.LOCATION:
      bg.Location location = headlessEvent.event;
      print('[BackgroundGeolocation] Headless LOCATION: $location');
      showNotification(
        title: '[BackgroundGeolocation] Headless LOCATION',
        body: 'speed: ${location.coords.speed} time: ${location.timestamp}',
      );
      break;
    case bg.Event.GEOFENCE:
      bg.GeofenceEvent geofenceEvent = headlessEvent.event;
      print('[BackgroundGeolocation] Headless GEOFENCE: $geofenceEvent');
      showNotification(
        title: '[BackgroundGeolocation] Headless GEOFENCE',
        body:
            'speed: ${geofenceEvent.location.coords.speed} time: ${geofenceEvent.location.timestamp}',
      );
      break;
    case bg.Event.GEOFENCESCHANGE:
      bg.GeofencesChangeEvent event = headlessEvent.event;
      print('[BackgroundGeolocation] Headless GEOFENCESCHANGE: $event');
      showNotification(
        title: '[BackgroundGeolocation] Headless GEOFENCESCHANGE',
        body: 'speed: $event',
      );
      break;
  }
}

/// Receive events from BackgroundFetch in Headless state
void backgroundFetchHeadlessTask() async {
  bg.Location location =
      await bg.BackgroundGeolocation.getCurrentPosition(samples: 1);
  await setupNotifications();
  print('[BackgroundFetch] Headless LOCATION: $location');
  showNotification(
    title: '[BackgroundFetch] Headless LOCATION',
    body: 'speed: ${location.coords.speed} time: ${location.timestamp}',
  );
  BackgroundFetch.finish();
}

/// Add a geofence to the plugin
void addGeofence({
  @required String id,
  @required double lat,
  @required double lng,
  @required int radius,
}) async {
  bg.Geofence geofence = bg.Geofence(
    identifier: id,
    latitude: lat,
    longitude: lng,
    radius: double.parse(radius.toString()),
    notifyOnEntry: true,
    notifyOnDwell: true,
    notifyOnExit: true,
  );

  try {
    await bg.BackgroundGeolocation.addGeofence(geofence);
  } catch (e) {
    print('Error adding geofence with id $id');
    return;
  }

  print('Successfully added geofence with id $id');
}

/// Initialize plugin to start tracking
Future<bool> startTracking({String env}) async {
  // Apply tracker url with username & device params for recognition by tracking server
  Map<String, dynamic> deviceParams = await bg.Config.deviceParams;

  await bg.BackgroundGeolocation.ready(bg.Config(
    desiredAccuracy: bg.Config.DESIRED_ACCURACY_HIGH,
    persistMode: bg.Config.PERSIST_MODE_GEOFENCE,
    logLevel: bg.Config.LOG_LEVEL_VERBOSE,
    stopOnTerminate: false,
    enableHeadless: true,
    startOnBoot: true,
    reset: true,
    autoSync: true,
    httpRootProperty: '.',
    locationTemplate:
        '{ "query": "mutation { insert_location(objects: { lat: <%= latitude %> lng: <%= longitude %> speed: <%= speed %> heading: <%= heading %> accuracy: <%= accuracy %> altitude: <%= altitude %> altitude_accuracy: <%= altitude_accuracy %> timestamp: \\\"<%= timestamp %>\\\" uuid: \\\"<%= uuid %>\\\" event: \\\"<%= event %>\\\" odometer: <%= odometer %> activity_type: \\\"<%= activity.type %>\\\" activity_confidence: <%= activity.confidence %> battery_level: <%= battery.level %> battery_is_charging: <%= battery.is_charging %> device_model: \\\"${deviceParams['device']['model']}\\\" device_platform: \\\"${deviceParams['device']['platform']}\\\" device_manufacturer: \\\"${deviceParams['device']['manufacturer']}\\\" device_version: \\\"${deviceParams['device']['version']}\\\" } ) { affected_rows } }" }',
    geofenceTemplate:
        '{ "query": "mutation { insert_location(objects: { lat: <%= latitude %> lng: <%= longitude %> speed: <%= speed %> heading: <%= heading %> accuracy: <%= accuracy %> altitude: <%= altitude %> altitude_accuracy: <%= altitude_accuracy %> timestamp: \\\"<%= timestamp %>\\\" uuid: \\\"<%= uuid %>\\\" event: \\\"<%= event %>\\\" odometer: <%= odometer %> activity_type: \\\"<%= activity.type %>\\\" activity_confidence: <%= activity.confidence %> battery_level: <%= battery.level %> battery_is_charging: <%= battery.is_charging %> device_model: \\\"${deviceParams['device']['model']}\\\" device_platform: \\\"${deviceParams['device']['platform']}\\\" device_manufacturer: \\\"${deviceParams['device']['manufacturer']}\\\" device_version: \\\"${deviceParams['device']['version']}\\\" geofence_identifier: \\\"<%= geofence.identifier %>\\\" geofence_action: \\\"<%= geofence.action %>\\\" } ) { affected_rows } }" }',
    url: '${appBase.hasuraUrl}',
    locationAuthorizationRequest: 'Always',
    locationAuthorizationAlert: {
      'titleWhenNotEnabled': 'Location services not enabled',
      'titleWhenOff': 'Location services are OFF',
      'instructions':
          'Location services required to start earning points. Please enable \'Always\' in location settings.',
      'cancelButton': 'Cancel',
      'settingsButton': 'Settings'
    },
    // Do not record location event if more than 300 meters/second since last
    // recorded event - Android only, iOS does not allow mock locations on device
    speedJumpFilter: 300,
    foregroundService: true,
    notificationPriority: bg.Config.NOTIFICATION_PRIORITY_MIN,
    notificationTitle: 'Zone Tracker',
    notificationText: 'Zone search underway',
    notificationChannelName: 'Zone Tracker',
  ));

  try {
    await bg.BackgroundGeolocation.startGeofences();
  } catch (e) {
    print(e);
  }

  // Register BackgroundGeolocation headless-task
  bg.BackgroundGeolocation.registerHeadlessTask(
      backgroundGeolocationHeadlessTask);

  // Register BackgroundFetch headless-task
  BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);

  // Fired whenever a location is recorded
  bg.BackgroundGeolocation.onLocation((bg.Location location) {
    print('[BackgroundGeolocation] onLocation $location');
    showNotification(
      title: '[BackgroundGeolocation] onLocation',
      body: 'speed: ${location.coords.speed} time: ${location.timestamp}',
    );
  }, (bg.LocationError error) {
    print('[onLocation] ERROR: $error');
  });

  bg.BackgroundGeolocation.onHttp((bg.HttpEvent event) {
    print('[BackgroundGeolocation] onHttp $event');
  });

  bg.BackgroundGeolocation.onGeofence((bg.GeofenceEvent event) {
    print('[BackgroundGeolocation] onGeofence $event');
    showNotification(
      title: '[BackgroundGeolocation] onGeofence',
      body:
          'speed: ${event.location.coords.speed} time: ${event.location.timestamp}',
    );
  });

  try {
    // force location permission dialog
    await bg.BackgroundGeolocation.getCurrentPosition(
      persist: false,
      samples: 1,
    );
  } catch (e) {
    print(e);
    // Permission was denied
    if (e.code == 1) return false;
  }

  return true;
}

Later in the application on a button tap before starting bicycle ride this is executed:

await bg.BackgroundGeolocation.start();

from flutter_background_geolocation.

christocracy avatar christocracy commented on August 26, 2024
  • Listen to all events before #ready

from flutter_background_geolocation.

joserocha3 avatar joserocha3 commented on August 26, 2024

With that change timestamp values now reflect the correct time. However, the geofence events are still not logged until app is reopened.

The log for this last run is available here. For this run I did not persist location, only geofence.

from flutter_background_geolocation.

joserocha3 avatar joserocha3 commented on August 26, 2024

With further observation the http requests for the geofence events is performed in the background, just not in perfect real-time. If I wait a minute eventually the request is sent for a group of pending events at once while in background. If I open the app it sends them all at that time. I have autoSync: true set.

from flutter_background_geolocation.

christocracy avatar christocracy commented on August 26, 2024

I see you closed this? it's no issue?

from flutter_background_geolocation.

joserocha3 avatar joserocha3 commented on August 26, 2024

Once I set the listeners before calling ready the timestamp issue was fixed.

After that there was a slight delay in the time the data was appearing on my server, but I was think I just being impatient. Will keep monitoring and reopen if needed.

Thanks for checking up on this issue.

from flutter_background_geolocation.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.