A Flutter plugin to get location updates in the background for both Android and iOS

Overview

Background Location

A Flutter plugin to get location updates in the background for both Android and iOS (Requires iOS 10.0+). Uses CoreLocation for iOS and FusedLocationProvider for Android

Getting Started

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

dependencies:
  background_location: ^0.8.1

2: Install packages from the command line:

$ flutter packages get

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

How to use

Import the package where you wanna use it.

import 'package:background_location/background_location.dart';

Request permissions from the user. You can use permission_handler for this

Set the notification title, message and icon (Android only). Use await or .then if you wanna start the location service immediatly after becuase its an asynchronous method

BackgroundLocation.setAndroidNotification(
	title: "Notification title",
        message: "Notification message",
        icon: "@mipmap/ic_launcher",
);

Set the interval between localisations in milliseconds (Android only). Use await or .then if you wanna start the location service immediatly after becuase its an asynchronous method

BackgroundLocation.setAndroidConfiguration(1000);

Start the location service. This will also ask the user for permission if not asked previously by another package.

BackgroundLocation.startLocationService();

Start location service by specifying distanceFilter. Defaults to 0 if not specified

BackgroundLocation.startLocationService(distanceFilter : 10);

You can also force the use of Android LocationManager instead of Google's FusedLocationProvider by setting the forceAndroidLocationManager property to true. If not specified, this defaults to false, which uses FusedLocationProvider if it is available, treating LocationManager as a fallback. This setting has no effect on iOS devices.

BackgroundLocation.startLocationService(forceAndroidLocationManager: true);

getLocationUpdates will trigger everytime the location updates on the device. Provide a callback function to getLocationUpdates to handle location update.

BackgroundLocation.getLocationUpdates((location) {
  print(location);
});

location is a Class exposing the following properties.

double latitude;
double longitude;
double altitude;
double bearing;
double accuracy;
double speed;
double time;
bool isMock;

To stop listening to location changes you can execute.

BackgroundLocation.stopLocationService();

Make sure to delcare all required permissions for both your android and ios app

info.plist

<key>NSLocationAlwaysAndWhenInUseUsageDescriptionkey>
<string>This app needs access to location.string>
<key>NSLocationAlwaysUsageDescriptionkey>
<string>This app needs access to location.string>
<key>NSLocationWhenInUseUsageDescriptionkey>
<string>This app needs access to location.string>
<key>UIBackgroundModeskey>
<array>
	<string>fetchstring>
	<string>locationstring>
array>

AndroidManifest.xml

">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/> 
Comments
  • Build fails in Flutter 3.0.0

    Build fails in Flutter 3.0.0

    Flutter doctor:

    Doctor summary (to see all details, run flutter doctor -v):
    [√] Flutter (Channel stable, 3.0.0, on Microsoft Windows [Version 10.0.22000.675], locale en-US)
    [√] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    [√] Chrome - develop for the web
    [X] Visual Studio - develop for Windows
        X Visual Studio not installed; this is necessary for Windows development.
          Download at https://visualstudio.microsoft.com/downloads/.
          Please install the "Desktop development with C++" workload, including all of its default components
    [√] Android Studio (version 2021.2)
    [√] IntelliJ IDEA Community Edition (version 2021.1)
    [√] VS Code (version 1.66.2)
    [√] Connected device (4 available)
    [√] HTTP Host Availability
    

    pubspec.yaml:

    dependencies:
        background_location: ^0.8.1
    

    Problem: When trying to build my app I am getting an error related to this library. The error in details follows

    e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\background_location-0.8.1\android\src\main\kotlin\com\almoullim\background_location\BackgroundLocationService.kt: (23, 1): Class 'BackgroundLocationService' is not abstract and does not implement abstract member public abstract fun onRequestPermissionsResult(p0: Int, p1: Array<(out) String!>, p2: IntArray): Boolean defined in io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener
    e: C:\flutter\.pub-cache\hosted\pub.dartlang.org\background_location-0.8.1\android\src\main\kotlin\com\almoullim\background_location\BackgroundLocationService.kt: (221, 5): 'onRequestPermissionsResult' overrides nothing
    
    FAILURE: Build failed with an exception.
    
    * What went wrong:
    Execution failed for task ':background_location:compileDebugKotlin'.
    > Compilation error. See log for more details
    
    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
    
    * Get more help at https://help.gradle.org
    
    BUILD FAILED in 33s
    Exception: Gradle task assembleDebug failed with exit code 1
    
    opened by ItsWajdy 29
  •  Class 'BackgroundLocationService' is not abstract and does not implement abstract member public abstract fun onRequestPermissionsResult

    Class 'BackgroundLocationService' is not abstract and does not implement abstract member public abstract fun onRequestPermissionsResult

    e: E:\flutter_3_0\.pub-cache\hosted\pub.dartlang.org\background_location-0.8.1\android\src\main\kotlin\com\almoullim\background_location\BackgroundLocationService.kt: (23, 1): Class 'BackgroundLocationService' is not abstract and does not implement abstract member public abstract fun onRequestPermissionsResult(p0: Int, p1: Array<(out) String!>, p2: IntArray): Boolean defined in io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener
    
    e: E:\flutter_3_0\.pub-cache\hosted\pub.dartlang.org\background_location-0.8.1\android\src\main\kotlin\com\almoullim\background_location\BackgroundLocationService.kt: (221, 5): 'onRequestPermissionsResult' overrides nothing
    
    opened by zohaibmushwani 11
  • Not Working in ios14

    Not Working in ios14

      void findLocation(int endTimeStamp) async {
        await BackgroundLocation.setNotificationTitle("Test Title");
        await BackgroundLocation.startLocationService();
        await BackgroundLocation.getLocationUpdates((location) async {
        	print(location.accuracy);
        });
      }
    

    this is my code working in android but not working in ios

    opened by Hisagar 11
  • Customize icon, text and optional action button.

    Customize icon, text and optional action button.

    The plugin works fine but there is no icon when I run example project. image Could you add some customization options for the icon, icon color, text and make "Stop location service" action optional?

    enhancement help wanted 
    opened by tomk9 11
  • Fix invalid cast error

    Fix invalid cast error

    Calling setAndroidConfiguration was passing a string to the "set_configuration" methodcall in BackgroundLocationPlugin.kt causing an invalid cast error

    The named parameter has also been removed for compatibility with the example

    opened by stevehayles 10
  • Does not receive background updates in emulator.

    Does not receive background updates in emulator.

    The package does not seem to receive background updates on Android when the emulator's screen is off(I presume the off button on the emulator is simply just the screen being off and not the device).

    The package, however, does work well if you have the screen on, the active app is google maps and the app is in the background.

    opened by Francismb 10
  • Not working for IOS

    Not working for IOS

    Error output from Xcode build: ↳ ** BUILD FAILED ** Xcode's output: ↳ /Users/user/Desktop/test/test/ios/Runner/GeneratedPluginRegistrant.m:10:9: fatal error: module 'background_location' not found @import background_location; ~~~~~~~^~~~~~~~~~~~~~~~~~~

    opened by GautamV234 8
  • Could you please migrating the plugin to the V2 embedding

    Could you please migrating the plugin to the V2 embedding

    The plugin background_location uses a deprecated version of the Android embedding. To avoid unexpected runtime failures, or future build failures, try to see if this plugin supports the Android V2 embedding. Otherwise, consider removing it since a future release of Flutter will remove these deprecated APIs. If you are plugin author, take a look at the docs for migrating the plugin to the V2 embedding: https://flutter.dev/go/android-plugin-migration.

    opened by EdisonJwa 7
  • Add an option to force the use of Android LocationManager

    Add an option to force the use of Android LocationManager

    This PR contains the same changes as #101 but also adds an explicit option to force LocationManager on android for users that prefer to not use google play services for location, such as developers looking to publish apps to F-Droid.

    This PR includes changes to the README to document the change and some testing has been done in a real app with no apparent issues.

    closes #101 closes #69 closes #14

    opened by MoralCode 7
  • Problem while updating project dependencies due to version conflicts of permission handler plugin used by plugin and project

    Problem while updating project dependencies due to version conflicts of permission handler plugin used by plugin and project

    background_location plugin depends on the permission handler 5.0.1+1 version and my other plugin needs to be updated which triggers the conflict with the permission handler version's plugin_platform_interface version. Therefore, I updated the permission handler plugin version. Now, It shows conflict with the background location plugin version as it still depends on the older version of the permission handler plugin version. Is there any kind of work going on regarding this issue? or I have to move on with another plugin to resolve this issue.

    opened by vaimikpatel2908 7
  • Unnecessary permission (ACCESS_BACKGROUND_LOCATION) call depending on usage

    Unnecessary permission (ACCESS_BACKGROUND_LOCATION) call depending on usage

    As some of you may know, requesting 'ACCESS_BACKGROUND_LOCATION' now requires that you submit for a special approval before your app is allowed on the the Play Store. This is because that permission is only meant to be used if the app needs background location without the user triggering it or when the app is not on screen (and not showing the user it's using the service). If you want location while the app is not in the foreground or screen is off (like a run tracking app) the 'proper' approach is to start a foreground service. That's what this plugin does, however, it relies on the user having their location permission set to 'All the time'. If it's set to 'While the app is in use' it will only get location a few times an hour.

    A clear and concise explanation of these recent platform changes is provided here: (https://medium.com/@adrian.kajda/restrictions-to-background-location-and-foreground-services-in-android-11-9501adcd5795).

    So for those of us who want to access frequent 'background location' without needing the 'ACCESS_BACKGROUND_LOCATION' permission and all the baggage that comes with it, there is an issue. But there's a fix! I adjusted 2 lines of code in this plugin and it allows for 'background location' access (technically not in the background because it's a service and showing the user a notification) while the app is not in the foreground.

    Both changes occur in the plugins Manifest.xml file: Change 1: Remove the 'ACCESS_BACKGROUND_LOCATION' permission. Change 2: Add 'android:foregroundServiceType="location" to the service tag. Like this: <service android:name=".LocationUpdatesService" android:foregroundServiceType="location" android:enabled="true" android:exported="true" android:permission="" />

    Setting the 'foregroundServiceType' to 'location' is critical. Without it, the system will not realize that the foreground service is meant for location and will therefore greatly limit any attempts to get location info. Important: In Android 11, you cannot start a foreground service for location in the background so if you use this make sure to start your service before the app is put into the background. If you need that type of functionality, that's what access_background_location is for.

    To finish up, I'm not sure if this plugin can be adjusted to allow for both scenarios mentioned above (I suspect not because of the inclusion of the 'ACCESS_BACKGROUND_LOCATION') but I wanted to submit this as an 'issue' just so people are aware. And maybe a better programmer than I am does know how to make it dynamic based on needs. And if not, perhaps it could be duplicated but with those minor changes to cover the 'running app' use case nicely.

    And a big thank you to Almoullim for writing this plugin!!! My apologies if this is a totally inappropriate use of submitting an issue!

    opened by bmason8 5
  • i try to install the library after that i got :background_locator:compileDebugKotlin

    i try to install the library after that i got :background_locator:compileDebugKotlin

    after trying to install the lib i got this error

    e: C:\src\flutter.pub-cache\hosted\pub.dartlang.org\background_locator-1.6.12\android\src\main\kotlin\rekab\app\background_locator\BackgroundLocatorPlugin.kt: (25, 1): Class 'BackgroundLocatorPlugin' is not abstract and does not implement abstract member public abstract fun onNewIntent(p0: Intent): Boolean defined in io.flutter.plugin.common.PluginRegistry.NewIntentListener e: C:\src\flutter.pub-cache\hosted\pub.dartlang.org\background_locator-1.6.12\android\src\main\kotlin\rekab\app\background_locator\BackgroundLocatorPlugin.kt: (215, 43): Type mismatch: inferred type is Map<Any, Any>? but Map<Any, Any> was expected e: C:\src\flutter.pub-cache\hosted\pub.dartlang.org\background_locator-1.6.12\android\src\main\kotlin\rekab\app\background_locator\BackgroundLocatorPlugin.kt: (215, 48): Type mismatch: inferred type is Map<Any, Any>? but Map<Any, Any> was expected e: C:\src\flutter.pub-cache\hosted\pub.dartlang.org\background_locator-1.6.12\android\src\main\kotlin\rekab\app\background_locator\BackgroundLocatorPlugin.kt: (224, 43): Type mismatch: inferred type is Map<Any, Any>? but Map<Any, Any> was expected e: C:\src\flutter.pub-cache\hosted\pub.dartlang.org\background_locator-1.6.12\android\src\main\kotlin\rekab\app\background_locator\BackgroundLocatorPlugin.kt: (224, 48): Type mismatch: inferred type is Map<Any, Any>? but Map<Any, Any> was expected e: C:\src\flutter.pub-cache\hosted\pub.dartlang.org\background_locator-1.6.12\android\src\main\kotlin\rekab\app\background_locator\BackgroundLocatorPlugin.kt: (243, 43): Type mismatch: inferred type is Map<Any, Any>? but Map<Any, Any> was expected e: C:\src\flutter.pub-cache\hosted\pub.dartlang.org\background_locator-1.6.12\android\src\main\kotlin\rekab\app\background_locator\BackgroundLocatorPlugin.kt: (243, 48): Type mismatch: inferred type is Map<Any, Any>? but Map<Any, Any> was expected e: C:\src\flutter.pub-cache\hosted\pub.dartlang.org\background_locator-1.6.12\android\src\main\kotlin\rekab\app\background_locator\BackgroundLocatorPlugin.kt: (266, 5): 'onNewIntent' overrides nothing e: C:\src\flutter.pub-cache\hosted\pub.dartlang.org\background_locator-1.6.12\android\src\main\kotlin\rekab\app\background_locator\BackgroundLocatorPlugin.kt: (275, 35): Type mismatch: inferred type is BinaryMessenger? but BinaryMessenger was expected e: C:\src\flutter.pub-cache\hosted\pub.dartlang.org\background_locator-1.6.12\android\src\main\kotlin\rekab\app\background_locator\IsolateHolderExtension.kt: (42, 27): Type mismatch: inferred type is BinaryMessenger? but BinaryMessenger was expected e: C:\src\flutter.pub-cache\hosted\pub.dartlang.org\background_locator-1.6.12\android\src\main\kotlin\rekab\app\background_locator\IsolateHolderService.kt: (269, 35): Type mismatch: inferred type is BinaryMessenger? but BinaryMessenger was expected e: C:\src\flutter.pub-cache\hosted\pub.dartlang.org\background_locator-1.6.12\android\src\main\kotlin\rekab\app\background_locator\pluggables\DisposePluggable.kt: (17, 51): Type mismatch: inferred type is BinaryMessenger? but BinaryMessenger was expected e: C:\src\flutter.pub-cache\hosted\pub.dartlang.org\background_locator-1.6.12\android\src\main\kotlin\rekab\app\background_locator\pluggables\InitPluggable.kt: (22, 55): Type mismatch: inferred type is BinaryMessenger? but BinaryMessenger was expected

    FAILURE: Build failed with an exception.

    • What went wrong: Execution failed for task ':background_locator:compileDebugKotlin'.

    Compilation error. See log for more details

    • Try:

    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

    • Get more help at https://help.gradle.org

    BUILD FAILED in 9s Exception: Gradle task assembleDebug failed with exit code 1

    opened by AbdrahmanKafo96 1
  • I got an error when I added

    I got an error when I added "background_location: ^0.8.1 " package to my project.

    I got this error when I added just the backgroud_location: ^0.8.1 package to my project:

     C:\SDK\flutter_sdk\.pub-cache\hosted\pub.dartlang.org\background_location-0.8.1\android\src\main\kotlin\com\almoullim\background_location\BackgroundLocationService.kt: (23, 1): Class 'BackgroundLocationService' is not abstract and does not implement abstract member public abstract fun onRequestPermissionsResult(p0: Int, p1: Array<(out) String!>, p2: IntArray): Boolean defined in io.flutter.plugin.common.PluginRegistry.RequestPermissionsResultListener
    e: C:\SDK\flutter_sdk\.pub-cache\hosted\pub.dartlang.org\background_location-0.8.1\android\src\main\kotlin\com\almoullim\background_location\BackgroundLocationService.kt: (221, 5): 'onRequestPermissionsResult' overrides nothing
    
    opened by SarahGhorbani 5
  • Add time filter similar to distance filter

    Add time filter similar to distance filter

    It is good to have a durationFiltee similar to distanceFilter in method startLocationService. Sometimes it is necessary to track geo position using not distance but duration (or even both of them).

    opened by bambinoua 0
  • Raise notification importance

    Raise notification importance

    I'm considering to use this package in an app, so I was reading thought the issues.

    Problem

    I found two issues concerning notification importance

    • https://github.com/Almoullim/background_location/issues/147
    • https://github.com/Almoullim/background_location/issues/96

    The subject of these issues is the fact that notification importance is currently set to low, which is not desirable as the system may not show, or hide the notification after a while: https://github.com/Almoullim/background_location/blob/6756c7c974721d5c2bf6894f04f20d2e08dc31b2/android/src/main/kotlin/com/almoullim/background_location/LocationUpdatesService.kt#L134

    Solution

    In issue https://github.com/Almoullim/background_location/issues/96 the author mentions a fork of this repository in which he implemented a fix. It can be seen in this commit:

    The changes can be seen here:

    https://github.com/willhaslett/background_location_important/commit/45797a7082c84910544cb0b99e239e3566cfee31

    It's basically changing NotificationManager.IMPORTANCE_LOW to NotificationManager.IMPORTANCE_DEFAULT.

    Can you please also implement it this in this repository?

    opened by dJani97 0
Releases(v0.9.0)
Owner
Ali Almoullim
Web Developer/Designer
Ali Almoullim
A Flutter plugin for updating location in background.

background_locator A Flutter plugin for getting location updates even when the app is killed. Refer to wiki page for install and setup instruction or

REKAB 270 Dec 29, 2022
Get Android App Updates Directly From the Source.

Obtainium Get Android App Updates Directly From the Source. Obtainium allows you to install and update Open-Source Apps directly from their releases p

Imran Remtulla 540 Dec 29, 2022
Klutter plugin makes it possible to write a Flutter plugin for both Android and iOS using Kotlin only.

The Klutter Framework makes it possible to write a Flutter plugin for both Android and iOS using Kotlin Multiplatform. Instead of writing platform spe

Gillian 33 Dec 18, 2022
A Flutter plugin which allows you to execute code in the background on Android and iOS.

Flutter Workmanager Flutter WorkManager is a wrapper around Android's WorkManager, iOS' performFetchWithCompletionHandler and iOS BGAppRefreshTask, ef

Flutter Community 699 Jan 5, 2023
Flutterbodydetection - A flutter plugin that uses MLKit on iOS/Android platforms to enable body pose and mask detection using Pose Detection and Selfie Segmentation APIs for both static images and live camera stream.

body_detection A flutter plugin that uses MLKit on iOS/Android platforms to enable body pose and mask detection using Pose Detection and Selfie Segmen

null 18 Dec 5, 2022
Flutter Local Notifications - Learn how to implement local notifications into both Android and iOS using flutter_local_notifications plugin.

Flutter Local Notifications Example Flutter Local Notifications - Learn how to implement local notifications into both Android and iOS using flutter_l

Sandip Pramanik 12 Nov 29, 2022
A flutter plugin that brings an in-background android app to the foreground

bg_launcher A flutter plugin that brings an in-background android app to the foreground (Android only) Restrictions on starting activities from the ba

Iheb Briki 5 Nov 25, 2022
A Flutter plugin that provides assets abstraction management APIs without UI integration, you can get assets (image/video/audio) on Android, iOS and macOS.

photo_manager Photo/Assets management APIs for Flutter without UI integration, you can get assets (image/video/audio) from Android, iOS and macOS. 提供相

FlutterCandies 526 Jan 4, 2023
A mobile application for both android and ios made for work out and fitness purpose

It's a mobile application for both android and ios made for work out and fitness purpose with many features you can read about here, but it can be used under all subject you want, well architected code and organized !

Gwhyyy 20 Dec 18, 2022
Telnyx flutter - A Flutter package for both android and iOS which helps developers with Telnyx API services

Telnyx Flutter A Flutter package for both android and iOS which helps developers

Kfir Matityahu 0 Jan 23, 2022
A Flutter Accident reporting App working in both iOS and Android

Flutter Accident Reporting App A Flutter Accident reporting App working in both iOS and Android.This project total size of all Dart files is 4714 bite

sk shamimul islam 32 Oct 13, 2022
A Basic Currency Converter made for both iOS and Android using the flutter.io platform

FlutterCurrencyConverter A Basic Currency Converter made for both iOS and Android using the flutter.io platform This app uses the ExchangeRate-API for

Carlo Gabriel Villalon Tapales 40 Nov 23, 2022
💳 A Flutter package for making payments via credo central. Provides support for both Android and iOS

?? Credo Package for Flutter TODO: Put a short description of the package here that helps potential users know whether this package might be useful fo

Samuel Abada 0 Dec 26, 2021
TicTacToe Using flutter. For both android and ios

mt_tictactoe A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if

Asim Sidd 3 Nov 27, 2022
A horoscope forecasting application for both Android and iOS

Zodoscope A Horoscope Forcasting Application Built with Flutter, for Android and iOS API used: http://horoscope-api.herokuapp.com/ Key Features All Zo

null 15 Sep 25, 2022
This project was writed with pure dart code,which means it's support both iOS and Android.

This project was writed with pure dart code,which means it's support both iOS and Android. Screenshot Todo show/hide animation Usage You can find the

吴述军 Brant 377 Dec 24, 2022
Notefy - Task Saving App for both Android and iOS

Assignment for Flutter Developers Goal of the assignment is to: -> Show the capa

Atabek 0 Jan 25, 2022
🎬 A movie catalog app for both Android & IOS ~ Flutter.io project in Dart | Dart, Bloc, Movies

Movie Catalog App ?? Browse through movies from the YIFY api Getting Started For help getting started with Flutter, view our online documentation. Tod

Jonas De Vrient 49 Nov 21, 2022
A Flutter plugin for changing the Home Screen, Lock Screen (or both) Wallpaper on Android devices.

wallpaper_manager A Flutter plugin for changing the Home Screen, Lock Screen (or both) Wallpaper(s) on Android devices. Usage Installation In the pubs

Aditya Mulgundkar 38 Nov 28, 2022