Comments (8)
Next beta arriving soon.
from flutter_background_geolocation.
Show me where you’re listening to #onLocation, #onGeofence relative to where you’re executing #ready.
from flutter_background_geolocation.
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.
- Listen to all events before #ready
from flutter_background_geolocation.
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.
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.
I see you closed this? it's no issue?
from flutter_background_geolocation.
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)
- Duplicate locations detected HOT 6
- About the changes to CoreLocation in iOS18, will it affect the function of the plugin? HOT 3
- Unhandled Exception: type '(HeadlessTask) => void' is not a subtype of type '(HeadlessEvent) => void' HOT 3
- Android lags at startup after accepting Geolocation Permissions HOT 3
- does not detect the state change from Stationary to Moving HOT 5
- Distance filter is not working in demo application - Closed ! HOT 9
- Warning: [deprecation] Registrar in PluginRegistry has been deprecated HOT 2
- Increasing aab-release size from 18.2 MB to 41.3 MB. HOT 1
- Can not get location data every 5 second HOT 2
- bg.Notification( ) => Failed to find icons. HOT 4
- Geofencing Actions stopped working after three days HOT 24
- How to disable data deletion after successful sending to the server? HOT 1
- Found Duplicate Location But Odometer was changed HOT 9
- Asking for always location permission every time app opens HOT 3
- Location updates stop after a period of time (Android 13) HOT 2
- Running geolocation without geofence HOT 1
- Activity type is "STILL" but is_movig: true HOT 13
- google has rejected our app, due to "health features" HOT 6
- Cannot update config URL using RPC HOT 5
- Blank screen after resuming from headless mode on Android 12, 13 and 14 HOT 6
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from flutter_background_geolocation.