flutter_background_geolocation

repository·master·Indexed 20 days ago

https://github.com/transistorsoft/flutter_background_geolocation

A high-performance background location tracking and geofencing SDK for Flutter on iOS and Android. It utilizes motion-detection intelligence via accelerometer, gyroscope, and magnetometer APIs to optimize battery life by automatically switching between moving and stationary states. The SDK supports circular and polygon geofencing, headless mode on Android, and integration with the background_fetch plugin for periodic tasks.

Tokens
19.5K
Snippets
56
Records
73
Agent score
71%

What's inside flutter_background_geolocation

  1. Overview of Background Geolocation for Flutter

    master

    Background Geolocation for Flutter is a sophisticated background location-tracking and geofencing SDK designed for iOS and Android. It features battery-conscious motion-detection intelligence using accelerometer, gyroscope, and magnetometer APIs to manage power consumption.

    Core Behavior:

    • Moving State: When motion is detected, location recording starts automatically based on your configured distanceFilter (in metres).
    • Stationary State: When the device is stationary, location services turn off automatically to conserve battery.
  2. Use the Demo Server for testing

    master

    The example app includes functionality to post tracking data to Transistor Software's demo server.

    When the app launches, register an organization and username. The data is sent to: https://tracker.transistorsoft.com

    You can view your results live on a map by navigating to: https://tracker.transistorsoft.com/<your-organization>

    NOTE

    The demo server is for testing purposes only. The organization name acts as a namespace to group your devices.

  3. Configure LocationFilter to preserve v4 behavior

    master

    In v5, a LocationFilter is enabled by default (geolocation.filter). This filter uses a Kalman filter and accuracy thresholds to smooth/adjust the location stream. If your app uses low/medium accuracy or operates in poor GPS conditions, the default settings might reject locations that were previously delivered in v4.

    To replicate the original v4 behavior (delivering all locations without pre-filtering), use LocationFilterPolicy.passThrough and set accuracy thresholds to 0 to disable the accuracy gate.

    BackgroundGeolocation.ready(Config(
      geolocation: GeoConfig(
        // ...your existing geolocation config...
        filter: LocationFilterConfig(
          policy: LocationFilterPolicy.passThrough,
          useKalman: false,                 // optional
          trackingAccuracyThreshold: 0,      // optional: disables accuracy gate
          odometerAccuracyThreshold: 0       // optional: disables accuracy gate
        )
      ),
    ));
  4. Understand Compound Config groups

    master

    In the Compound Config model, settings are grouped into specific Dart classes to improve clarity and extensibility. Use these classes to organize your BackgroundGeolocation.ready() configuration:

    GroupClass NameDescription
    geolocationGeoConfigLocation and geofencing options
    appAppConfigApp lifecycle and scheduling
    httpHttpConfigHTTP sync, batching, headers, etc.
    loggerLoggerConfigDebug, log-level, log retention
    activityActivityConfigActivity recognition, stop detection
    persistencePersistenceConfigData storage, max days, max records
  5. Configure Cocoapods for iOS Installation

    master

    If you are not using Swift Package Manager, you must configure your ios/Podfile to use static linkage. Append :linkage => :static to the use_frameworks! declaration. Failure to do this will result in a build error regarding transitive dependencies including statically linked binaries (TSBackgroundGeolocation.xcframework).

    target 'Runner' do
      use_frameworks! :linkage => :static
      # ...
    end
  6. Configure Google Play Services Location version in Android

    master

    You can control the version of Google's play-services:location used by the plugin by setting the playServicesLocationVersion variable in your root Android build file. This is useful if you need a specific version or higher.

    // In android/build.gradle
    ext {
        playServicesLocationVersion = "21.3.0"  // or higher / as desired
    }
    // In android/build.gradle.kts
    allprojects {
       ext {
           set("playServicesLocationVersion", "21.3.0") // or higher / as desired
       }
    }
  7. Migrate from Flat Config to Compound Config

    master

    Version 5.0.0 introduced a Compound Config format to replace the legacy "flat" configuration structure. While the legacy flat style remains supported for backward compatibility, new features may only be available in the compound structure.

    Migration Steps:

    1. Update dependency: Ensure you are using flutter_background_geolocation v5.0.0 or later.
    2. Android Cleanup: Remove custom maven url entries from android/build.gradle. The local libs repositories for flutter_background_geolocation and background_fetch are no longer required.
    3. Group Options: Move related keys into their respective configuration classes (e.g., GeoConfig, HttpConfig, AppConfig).
    4. Replace Keys: Pass the new compound config objects into BackgroundGeolocation.ready(Config(...)) instead of passing all options at the top level.
    // After (Compound Config)
    BackgroundGeolocation.ready(Config(
      geolocation: GeoConfig(
        desiredAccuracy: DesiredAccuracy.high,
        distanceFilter: 50,
      ),
      app: AppConfig(
        stopOnTerminate: false,
        startOnBoot: true,
      ),
      http: HttpConfig(
        url: "https://my.server.com/locations",
        headers: { "Authorization": "Bearer TOKEN" },
      ),
      logger: LoggerConfig(
        logLevel: LogLevel.verbose,
        debug: true,
      ),
    ));
  8. Customize the iOS launch screen assets

    master

    To change the image displayed during the app's launch on iOS, you can replace the existing image files in the example/ios/Runner/Assets.xcassets/LaunchImage.imageset/ directory with your own assets.

    Alternatively, you can manage these assets using Xcode:

    1. Open the iOS project in Xcode by running open ios/Runner.xcworkspace from your terminal.
    2. In the Xcode Project Navigator, navigate to Runner/Assets.xcassets.
    3. Drag and drop your desired images into the asset catalog to replace the current launch images.
    open ios/Runner.xcworkspace
  9. Configure Permissions and Background Modes for iOS

    master

    To enable background geolocation on iOS, you must configure both Xcode Background Modes and Info.plist permissions.

    1. Enable Background Modes in Xcode

    Open ios/Runner/Runner.xcworkspace in Xcode and enable the following under Signing & Capabilities > Background Modes:

    • Location updates
    • Background fetch
    • Audio (Optional: only required if using debug-mode sound FX)

    2. Add Permissions to Info.plist

    You must add the following keys to your ios/Runner/Info.plist with descriptive strings explaining why your app requires these permissions:

    <plist>
    <dict>
    +    <key>NSMotionUsageDescription</key>
    +    <string>Motion usage description</string>
    +    <key>NSLocationWhenInUseUsageDescription</key>
    +    <string>When in use description</string>
    +    <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
    +    <string>Always/When in use description</string>
    
    +    <key>UIBackgroundModes</key>
    +    <array>
    +        <string>fetch</string>
    +        <string>location</string>
    +    </array>
    
    +    <key>BGTaskSchedulerPermittedIdentifiers</key>
    +    <array>
    +        <string>com.transistorsoft.fetch</string>
    +    </array>
    </dict>
    </plist>
  10. Install flutter_background_geolocation on Android

    master

    To integrate the plugin into your Android application, you must apply the plugin's Gradle script and configure resource shrinking.

    Important: You MUST set shrinkResources to false in your release build type to prevent the plugin from being stripped out during the build process.

    // In android/app/build.gradle
    Project background_geolocation = project(':flutter_background_geolocation')
    apply from: "${background_geolocation.projectDir}/background_geolocation.gradle"
    
    android {
        buildTypes {
            release {
                minifyEnabled true
                shrinkResources false   // <-- REQUIRED !!!
            }
        }
    }
    // In android/app/build.gradle.kts
    val backgroundGeolocation = project(":flutter_background_geolocation")
    apply { from("${backgroundGeolocation.projectDir}/background_geolocation.gradle") }
    
    android {
        buildTypes {
            release {
                isMinifyEnabled = true
                isShrinkResources = false   // <-- REQUIRED !!!
            }
        }
    }
  11. Configure the Android license key

    master

    While the plugin is fully functional in DEBUG builds without a license, you must add a license key to your AndroidManifest.xml for production/release use.

    Note for v5+ users: Version 5.0.0 and later require a new license key format. These new keys automatically unlock purchased add-ons like Polygon Geofencing, Huawei HMS Adapter, and Firebase Adapter without needing separate keys.

    <!-- In android/app/src/main/AndroidManifest.xml -->
    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.your.package.id">
      <application>
        <!-- flutter_background_geolocation licence -->
        <meta-data android:name="com.transistorsoft.locationmanager.license" android:value="YOUR_LICENCE_KEY_HERE" />
      </application>
    </manifest>