How I achieved Flutter Background Location Tracking ? (even when app is being killed)
After extensive research and trial, I recently discovered a reliable method for achieving background location tracking in Flutter something many other developers have been pursuing as well. Although there’s a package on pub.dev that provides background location tracking and geolocation functionalities, it comes with a license fee of around $375/year per app. For my project, this wasn’t feasible, so I set out to develop an alternative approach using Android’s native capabilities.
I realized that the most robust way to ensure consistent location tracking in the background, even when the app is closed, was through a foreground service. Unlike other services that may be terminated by Android OS to conserve resources, a foreground service has greater longevity. I configured it to display latitude and longitude updates in the notification body as confirmation that background location tracking was working correctly.
Once I achieved reliable location tracking, I integrated this code into the Android section of my Flutter app. Additionally, I enabled it to push location data to Firebase directly from the foreground service. One key insight from this journey was understanding why certain packages fail to maintain location tracking when the app is terminated. Most packages run on the main UI thread, which ceases once the app is closed. In contrast, the foreground service operates on a separate thread, allowing it to continue running independently of the app’s lifecycle. Therefore, any API calls or data pushes to Firebase should be implemented within the service thread to ensure they persist, even if the app is killed.
This approach has proven highly effective for continuous background location tracking in Flutter applications, providing a cost-effective alternative to third-party packages. While I won’t be diving into the code specifics here, I wanted to share this journey to hopefully inspire other Flutter developers facing similar challenges.
Subscribe to my newsletter
Read articles from Anmol Singh Tuteja directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by