flutter_background_geolocation 1.0.9

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 94

flutter_background_geolocation #


The most sophisticated background location-tracking & geofencing module with battery-conscious motion-detection intelligence for iOS and Android.

The plugin's Philosophy of Operation is to use motion-detection APIs (using accelerometer, gyroscope and magnetometer) to detect when the device is moving and stationary.

  • When the device is detected to be moving, the plugin will automatically start recording a location according to the configured distanceFilter (meters).

  • When the device is detected be stationary, the plugin will automatically turn off location-services to conserve energy.

Also available for Cordova, React Native, NativeScript and pure native apps.


The Android module requires purchasing a license. However, it will work for DEBUG builds. It will not work with RELEASE builds without purchasing a license.

(2018) This plugin is supported full-time and field-tested daily since 2013.


Google Play

Home Settings

Contents #

🔷 Installing the Plugin #

📂 pubspec.yaml:

Note: See Versions for latest available version.

dependencies:
  flutter_background_geolocation: '^0.3.4'

Or latest from Git: #

dependencies:
  flutter_background_geolocation:
    git:
      url: https://github.com/transistorsoft/flutter_background_geolocation.git

🔷 Setup Guides #

🔷 Using the plugin #

import 'package:flutter_background_geolocation/flutter_background_geolocation.dart' as bg;

⚠ī¸ Note as bg in the import. This is important to namespace the plugin's classes, which often use common class-names such as Location, Config, State. You will access every flutter_background_geolocation class with the prefix bg (ie: "background geolocation").

🔷 Example #

Full Example

There are three main steps to using BackgroundGeolocation:

  1. Wire up event-listeners.
  2. Configure the plugin with #ready.
  3. #start the plugin.

import 'package:flutter_background_geolocation/flutter_background_geolocation.dart' as bg;

class _MyHomePageState extends State<MyHomePage> {

  @override
  void initState() {
    ////
    // 1.  Listen to events (See docs for all 12 available events).
    //

    // Fired whenever a location is recorded
    bg.BackgroundGeolocation.onLocation((bg.Location location) {
      print('[location] - $location');
    });

    // Fired whenever the plugin changes motion-state (stationary->moving and vice-versa)
    bg.BackgroundGeolocation.onMotionChange((bg.Location location) {
      print('[motionchange] - $location');
    });

    // Fired whenever the state of location-services changes.  Always fired at boot
    bg.BackgroundGeolocation.onProviderChange((bg.ProviderChangeEvent event) {
      print('[providerchange] - $event');
    });

    ////
    // 2.  Configure the plugin
    //
    bg.BackgroundGeolocation.ready(bg.Config(
        desiredAccuracy: bg.Config.DESIRED_ACCURACY_HIGH,
        distanceFilter: 10.0,
        stopOnTerminate: false,
        startOnBoot: true,
        debug: true,
        logLevel: bg.Config.LOG_LEVEL_VERBOSE,
        reset: true
    )).then((bg.State state) {
      if (!state.enabled) {
        ////
        // 3.  Start the plugin.
        //
        bg.BackgroundGeolocation.start();
      }
    });
  }
}

ℹī¸ NOTE: The configuration {} provided to the #ready method is applied only when your app is first booted — for every launch thereafter, the plugin will automatically load the last known configuration from persistant storage. If you wish to force the #ready method to always apply the supplied config {}, you can specify reset: true

bg.BackgroundGeolocation.ready(bg.Config(
  reset: true,  // <-- true to always apply the supplied config
  distanceFilter: 10.0
)).then((bg.State state) {
  print('[ready] success: $state);
});

⚠ī¸ Do not execute any API method which will require accessing location-services until the callback to **#ready* executes (eg: #getCurrentPosition, #watchPosition, #start).

🔷 Demo Application #

A fully-featured Demo App is available in the repo in the /example folder.

Google Play

Home Settings

🔷 Simple Testing Server

A simple Node-based web-application with SQLite database is available for field-testing and performance analysis. If you're familiar with Node, you can have this server up-and-running in about one minute.

License #

The MIT License (MIT)

Copyright (c) 2018 Chris Scott, Transistor Software

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CHANGELOG #

[1.0.9] - 2019-06-17

  • [Fixed] Android bug with getCurrentPosition and maximumAge, Fixes #80.
  • [Fixed] Odometer issues: clear odometer reference location on #stop, #startGeofences.
  • [Fixed] Odometer issues: Android must persist its odometer reference location since the foreground-service is no longer long-lived and the app may be terminated between motionchange events.
  • [Fixed] Return Service.START_REDELIVER_INTENT from HeartbeatService. Fixes #79 to prevent null Intent being delivered to HeartbeatService.
  • [Added] Implement Android LocationSettingsRequest. Determines if device settings is currently configured according to the plugin's desired-settings (eg: gps enabled, location-services enabled). If the device settings differs, an automatic dialog will perform the required settings changes automatically when user clicks [OK].
  • [Fixed] Android triggerActivities was not implemented refactor of 1.x.

[1.0.8] - 2019-06-04

  • [Fixed] Android destroyLocations callback was being executed in background-thread.
  • [Fixed] When Android geofence API receives a GEOFENCE_NOT_AVAILABLE error (can occur is Wifi is disabled), geofences must be re-registered.
  • [Fixed] Android Config.disableStopDetection was not implemented.

[1.0.7] - 2019-05-13

  • [Fixed] Android issue with Firebase Adapter support not working when app is terminated.

[1.0.6] - 2019-05-12

  • [Added] New Android config Config.scheduleUseAlarmManager to force Android scheduler to use more precise AlarmManager instead of JobScheduler.
  • [Added] Support for background_geolocation_firebase adapter.

[1.0.5] - 2019-05-10

  • [Changed] Rollback android-permissions version back to 0.1.8. It relies on support-annotations@28. This isn't a problem if one simply upgrades their targetSdkVersion but the support calls aren't worth the hassle, since the latest version doesn't offer anything the plugin needs.

[1.0.4] - 2019-05-09

  • [Changed] Update docs.

[1.0.3] - 2019-05-08

  • [Fixed] Dart analysis warnings, re: initializing null values in new Notification class.

[1.0.2] - 2019-05-08

  • [Fixed] iOS: changing pauseslocationUpdatesAutomatically was not being applied.
  • [Changed] reset parameter provided to #ready has now been default to true. This causes too many support issues for people using the plugin the first time.
  • [Fixed] Android threading issue where 2 distinct SingleLocationRequest were issued the same id. This could result in the foreground service quickly starting/stopping until locationTimeout expired.
  • [Fixed] Android issue where geofences could fail to query for new geofences-in-proximity after a restart.
  • [Fixed] Android issues re-booting device with location-services disabled or location-authorization revoked.
  • [Added] Implement support for Custom Android Notification Layouts.
  • [Fixed] Android bug where Service repeatedly stops / starts after rebooting device with plugin in moving state.
  • [Fixed] Android scheduler bug. When app is terminated & restarted during a scheduled ON period, tracking-service does not restart.
  • [Fixed] Android headless heartbeat events were failing (incorrect Context was supplied to the event).

[1.0.1] - 2019-04-09

  • [Fixed] iOS: Incorrect return type BOOL from native method stopBackgroundTask. Should have been int.
  • [Changed] Add Geofence test panel in example Settings screen. Allows to add a series of test-geofences along the iOS simulator Freeway Drive route.

[1.0.0] - 2019-04-05

  • [RELEASE] Release 1.0.0

[1.0.0-rc.4] - 2019-03-31

  • [Fixed] Android: Another NullPointerException with Bundle#getExtras.

[1.0.0-rc.3] - 2019-03-29

  • [Fixed] Android NullPointerException with Bundle#getExtras (#674).
  • [Fixed] Android not persisting providerchange location when location-services re-enabled.

[1.0.0-rc.2] - 2019-03-27

  • [Fixed] An Android foreground-service is launched on first install and fails to stop.

[1.0.0-rc.1] - 2019-03-25

Breaking Changes #

  • [Changed] The license format has changed. New 1.0.0 licenses are now available for customers in the product dashboard.

Fixes #

  • [Fixed] iOS missing native destroyLog implementation (thanks to @joserocha3)
  • [Fixed] Missing Dart implementation for requestPermission method (thanks to @joserocha3)
  • [Fixed] Logic bugs in MotionActivity triggering between stationary / moving states.
  • [Fixed] List.map Bug in Dart api addGeofences.

New Features #

  • [Added] Android implementation for useSignificantChangesOnly Config option. Will request Android locations without the persistent foreground service. You will receive location updates only a few times per hour: useSignificantChangesOnly: true:

useSignificantChangesOnly: false:

  • [Added] Android now implements a "stationary geofence", just like iOS. It currently acts as a secondary triggering mechanism along with the current motion-activity API. You will hear the "zap" sound effect when it triggers. This also has the fortunate consequence of allowing mock-location apps (eg: Lockito) of being able to trigger tracking automatically.

  • [Added] The SDK detects mock locations and skips trigging the stopTimeout system, improving location simulation workflow.

  • [Added] Android-only Config option geofenceModeHighAccuracy for more control over geofence triggering responsiveness. Runs a foreground-service during geofences-only mode (#startGeofences). This will, of course, consume more power.

await BackgroundGeolocation.ready(Config
  geofenceModeHighAccuracy: true,
  desiredAccuracy: Config.DESIRED_ACCURACY_MEDIUM,
  locationUpdateInterval: 5000,
  distanceFilter: 50
));

BackgroundGeolocation.startGeofences();
  • [Added] Android implementation of startBackgroundTask / stopBackgroundTask. This implementation uses a foreground-service. I've tried using Android's JobService but these tasks are queued by the OS and run only periodically.
  // an Android foreground-service has just launched (in addition to its persistent notification).
  int taskId = await BackgroundGeolocation.startBackgroundTask();

  // Do any work you like -- it's guaranteed to run, regardless of background/terminated.
  // Your task has exactly 30s to do work before the service auto-stops itself.

  // Execute an HTTP request to test an async operation.
  String url = "http://tracker.transistorsoft.com/devices?company_token=$_username";
  String result = await http.read(url).then((String result) {
    print("[http test] success: $result");
    // Terminate the foreground-service.
    BackgroundGeolocation.stopBackgroundTask(taskId);
  }).catchError((dynamic error) {
    print("[http test] failed: $error");
    // Always be sure to stop your tasks, just like iOS.
    BackgroundGeolocation.stopBackgroundTask(taskId);
  });

Logging for background-tasks looks like this (when you see an hourglass, a foreground-service is active)

 [BackgroundTaskManager onStartJob] âŗ startBackgroundTask: 6
 .
 .
 .
 [BackgroundTaskManager$Task stop] âŗ stopBackgroundTask: 6
  • [Added] New custom Android debug sound FX. More documentation will be added to the docs but here's a basic description from the code:
    public static final String LOCATION_RECORDED        = OOOOIII;
    public static final String LOCATION_SAMPLE          = CLICK_TAP_DONE;
    public static final String LOCATION_ERROR           = DIGI_WARN;

    public static final String MOTIONCHANGE_FALSE       = MARIMBA_DROP;
    public static final String MOTIONCHANGE_TRUE        = CHIME_SHORT_CHORD_UP;
    public static final String STATIONARY_GEOFENCE_EXIT = ZAP_FAST;

    public static final String STOP_TIMER_ON            = CHIME_BELL_CONFIRM;
    public static final String STOP_TIMER_OFF           = BELL_DING_POP;

    public static final String HEARTBEAT                = PEEP_NOTE;

    public static final String GEOFENCE_ENTER           = BEEP_TRIP_UP_DRY;
    public static final String GEOFENCE_DWELL           = BEEP_TRIP_UP_ECHO;
    public static final String GEOFENCE_EXIT            = BEEP_TRIP_DRY;

    public static final String WARNING                  = DIGI_WARN;
    public static final String ERROR                    = MUSIC_TIMPANI_ERROR;

⚠ī¸ These debug sound FX consume about 1.4MB in the plugin's tslocationmanager.aar. These assets can easily be stripped in your release builds by adding the following gradle task to your app/build.gradle (I'm working on an automated solution within the context of the plugin's build.gradle; so far, no luck). Big thanks to @mikehardy.

/**
 * Purge flutter_background_geolocation debug sounds from release build.
 */
def purgeBackgroundGeolocationDebugResources(applicationVariants) {
    applicationVariants.all { variant ->
        if (variant.buildType.name == 'release') {
            variant.mergeResources.doLast {
                delete(fileTree(dir: variant.mergeResources.outputDir, includes: ['raw_tslocationmanager*']))

            }
        }
    }
}

android {
    //Remove debug sounds from background_geolocation plugin
    purgeBackgroundGeolocationDebugResources(applicationVariants)

    compileSdkVersion rootProject.ext.compileSdkVersion
    .
    .
    .
}

Removed #

  • [Changed] Removed Android config option activityRecognitionInterval. The Android SDK now uses the more modern ActivityTransistionClient API which is a higher level wrapper for the traditional ActivityReconitionClient. AcitvityTransitionClient does not accept a polling interval, thus actiivtyRecognitionInterval is now unused. Also, ActivityTransitionClient emits similar on_foot, in_vehicle events but no longer provides a confidence, thus confidence is now reported always as 100. If you've been implementing your own custom triggering logic based upon confidence, it's now pointless. The ActivityTransitionClient will open doors for new features based upon transitions between activity states.
╔═════════════════════════════════════════════
║ Motion Transition Result
╠═════════════════════════════════════════════
╟─ 🔴  EXIT: walking
╟─ 🎾  ENTER: still
╚═════════════════════════════════════════════

Maintenance #

  • [Changed] Update android-permissions dependency to 0.1.8.

example/README.md

flutter_background_geolocation_example #

Demonstrates how to use the flutter_background_geolocation plugin.

Getting Started #

For help getting started with Flutter, view our online documentation.

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_background_geolocation: ^1.0.9

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:flutter_background_geolocation/flutter_background_geolocation.dart';
  
Version Uploaded Documentation Archive
1.0.9 Jun 17, 2019 Go to the documentation of flutter_background_geolocation 1.0.9 Download flutter_background_geolocation 1.0.9 archive
1.0.8 Jun 4, 2019 Go to the documentation of flutter_background_geolocation 1.0.8 Download flutter_background_geolocation 1.0.8 archive
1.0.7 May 24, 2019 Go to the documentation of flutter_background_geolocation 1.0.7 Download flutter_background_geolocation 1.0.7 archive
1.0.6 May 23, 2019 Go to the documentation of flutter_background_geolocation 1.0.6 Download flutter_background_geolocation 1.0.6 archive
1.0.5 May 10, 2019 Go to the documentation of flutter_background_geolocation 1.0.5 Download flutter_background_geolocation 1.0.5 archive
1.0.4 May 9, 2019 Go to the documentation of flutter_background_geolocation 1.0.4 Download flutter_background_geolocation 1.0.4 archive
1.0.3 May 8, 2019 Go to the documentation of flutter_background_geolocation 1.0.3 Download flutter_background_geolocation 1.0.3 archive
1.0.2 May 8, 2019 Go to the documentation of flutter_background_geolocation 1.0.2 Download flutter_background_geolocation 1.0.2 archive
1.0.1 Apr 9, 2019 Go to the documentation of flutter_background_geolocation 1.0.1 Download flutter_background_geolocation 1.0.1 archive
1.0.0 Apr 5, 2019 Go to the documentation of flutter_background_geolocation 1.0.0 Download flutter_background_geolocation 1.0.0 archive

All 38 versions...

Popularity:
Describes how popular the package is relative to other packages. [more]
89
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
95
Overall:
Weighted score of the above. [more]
94
Learn more about scoring.

We analyzed this package on Jun 17, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.3.2
  • pana: 0.12.18
  • Flutter: 1.5.4-hotfix.2

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Maintenance issues and suggestions

Support latest dependencies. (-5 points)

The version constraint in pubspec.yaml does not support the latest published versions for 1 dependency.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.28.0 <3.0.0
background_fetch ^0.2.0 0.2.0
device_info ^0.4.0 0.4.0+2
flutter 0.0.0
Transitive dependencies
collection 1.14.11
meta 1.1.6 1.1.7
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8