Last active
March 11, 2020 15:33
-
-
Save Gnzlt/d711f30207e08e5ea3a04b08a7aaef6f to your computer and use it in GitHub Desktop.
Android Location LiveData in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example | |
import android.arch.lifecycle.LiveData | |
import android.content.Context | |
import android.location.Location | |
import com.google.android.gms.location.LocationCallback | |
import com.google.android.gms.location.LocationRequest | |
import com.google.android.gms.location.LocationResult | |
import com.google.android.gms.location.LocationServices | |
import com.google.android.gms.tasks.OnSuccessListener | |
class LocationLiveData(context: Context) : LiveData<Location>() { | |
private val locationClient = LocationServices.getFusedLocationProviderClient(context) | |
private val locationCallback = object : LocationCallback(), OnSuccessListener<Location> { | |
override fun onLocationResult(locationResult: LocationResult?) { | |
locationResult?.locations?.firstOrNull()?.let { value = it } | |
} | |
override fun onSuccess(location: Location?) { | |
location?.let { value = it } | |
} | |
} | |
override fun onActive() { | |
// Try to immediately find a location | |
locationClient.lastLocation.addOnSuccessListener(locationCallback) | |
// Request updates if there’s someone observing | |
if (hasActiveObservers()) { | |
locationClient.requestLocationUpdates(LocationRequest(), locationCallback, null) | |
} | |
} | |
override fun onInactive() { | |
locationClient.removeLocationUpdates(locationCallback) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment