Search code examples
androidlocationforeground-service

Android Location updates not updating


I am using FusedLocationProviderClient for listening location updates. And I am using foreground service for obtaining location updates when the user is not inside the app.

class DriverService : LifecycleService() {
   
   private lateinit var fusedLocationClient: FusedLocationProviderClient
   private lateinit var locationCallback: LocationCallback
   
   .....
   
   override fun onCreate() {
        super.onCreate()

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    locationCallback =
        object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult?) {
                locationResult ?: return
                for (location in locationResult.locations) {
                    lifecycleScope.launch {
                        repository.sendCoordinates(
                            lat = location.latitude,
                            long = location.longitude,
                            bearing = location.bearing
                        )
                    }
                }
            }
        }
    startLocationUpdates()
   } 

   private fun startLocationUpdates() {
      val locationRequest = LocationRequest()
      locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
      locationRequest.fastestInterval = 500
      fusedLocationClient.requestLocationUpdates(
          locationRequest,
          locationCallback,
          Looper.getMainLooper()
      )
   }
}

When I am inside the app it is working perfectly fine but as soon as I quit the application, location updates stop working.


Solution

  • I thought if I used the foreground service, I would not have to get background permission. But I couldn't get location updates when I leave the application, even though the service was running. After I had changed "While using the app" permission to "All the time" permission, it worked.