How can I create a location tracking service in Android that runs in the background, even when the app is completely killed? The service should start whenever the device's location changes by 100 meters and should stop if the device is stationary. Additionally, I need the service to be as battery efficient as possible. I have tried using a foreground service with a combination of the Activity Recognition API but it does not seem to work when the app is completely killed. Can someone please guide me on how to achieve this task in Android?
Here is my basic location service that updates the location in the background:
class LocationService : Service() {
private val locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
locationResult ?: return
for (location in locationResult.locations) {
// do something with the location here
}
}
}
override fun onCreate() {
val locationRequest = LocationRequest().apply {
interval = 10000
fastestInterval = 5000
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
val client = LocationServices.getFusedLocationProviderClient(this)
val locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
locationResult ?: return
for (location in locationResult.locations) {
// do something with the location here
}
}
}
client.requestLocationUpdates(locationRequest, locationCallback, null)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return START_STICKY
}}
One possible solution is to use the Transition API in combination with a broadcast receiver. The Transition API can listen for changes in activity, such as when the device starts moving, and start the service in the background. Additionally, we can use a broadcast receiver to listen for location updates, and restart the service if the device's location changes by 100 meters or more. However, I am not sure if this will work in the case when the app is completely killed, and need guidance on how to properly implement this solution or any other solution you have in mind to create a "kill-proof" location tracking service.