I'm trying to get some location updates and save them to the database.
My problem is that sometimes it works, sometimes it does not.
What I do now is I start a Work Manager like this:
val uploadWorkRequest: PeriodicWorkRequest =
PeriodicWorkRequestBuilder<ListenableLocationUpdateWorker>(
15, TimeUnit.MINUTES
).build()
WorkManager
.getInstance(this)
.enqueueUniquePeriodicWork(
PERIODIC_LOCATION_TAG,
ExistingPeriodicWorkPolicy.REPLACE,
uploadWorkRequest
)
ListenableLocationUpdateWorker looks like this:
val repository = Repository(context)
private var fusedLocationClient: FusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(context)
private val locationRequest: LocationRequest
get() {
return LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 5000).build()
}
@SuppressLint("MissingPermission")
override fun startWork(): ListenableFuture<Result> {
return CallbackToFutureAdapter.getFuture {
fusedLocationClient.lastLocation.addOnSuccessListener { lastLocation ->
if (lastLocation != null) {
val locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
fusedLocationClient.removeLocationUpdates(this)
repository.Insert(locationResult)
it.set(Result.success())
}
}
fusedLocationClient.requestLocationUpdates(
locationRequest,
locationCallback,
Looper.getMainLooper()
)
} else {
it.set(Result.failure())
}
}
}
}
Main problem is that sometimes there are no location, or work manager just haven't started.
Now it works only when I open the app, so no background work here.
How do I make it right?