Search code examples
androidkotlinandroid-workmanager

Get current location using workers


I have an application similar to Cabify (drivers) and I try to get the current location of the driver, I had done this with IntentService, but now I want to use workers, but I don't know why when I try to get the location, this is null, any ideas ?

My doWork function is something like this

override suspend fun doWork(): Result {
    if (applicationContext.needPermission(Manifest.permission.ACCESS_FINE_LOCATION)) {
        Report.exception("No GPS permission")
        return Result.failure()
    }

    val fusedLocationClient: FusedLocationProviderClient =
        LocationServices.getFusedLocationProviderClient(context)
    val loc = fusedLocationClient.lastLocation?.await() ?: return Result.retry()

    onLocationWork(loc)

    return Result.success()
}

Solution

  • It just means that your last location is unknown and you need to cover such cases. Like

    val lastKnownLocation = fusedClient.lastKnownLocation ?: requestCurrentLocation()
    

    In your requestCurrentLocation()

    val locationRequest = LocationRequest.create()
        .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY) // your accuracy here
        .setInterval(5000L) // 5 sec, your interval here
        .setFastestInterval(5000L) // 5 sec, your interval here
    fusedClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper())
    

    If you need to get the location only once and it's not about listening to it all the time, you should wrap this code with a suspendCancellableCoroutine or a callbackFlow and subscribe to updates, when you get a location - remove all updates and the location callback.