Add findCurrentLocation

feature/top10
Aurelien Hubert 7 years ago
parent 2c1e66a155
commit 7ecfc7e680
  1. 26
      app/src/main/java/net/pokeranalytics/android/util/LocationManager.kt

@ -44,6 +44,8 @@ class LocationManager(private var context: Context) {
// Call findCurrentPlace and handle the response (first check that the user has granted permission). // Call findCurrentPlace and handle the response (first check that the user has granted permission).
if (ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
val placeResponse = placesClient.findCurrentPlace(request) val placeResponse = placesClient.findCurrentPlace(request)
placeResponse.addOnCompleteListener { task -> placeResponse.addOnCompleteListener { task ->
val places = ArrayList<PlaceLikelihood>() val places = ArrayList<PlaceLikelihood>()
if (task.isSuccessful) { if (task.isSuccessful) {
@ -142,7 +144,31 @@ class LocationManager(private var context: Context) {
// If we don't have the permission, return null // If we don't have the permission, return null
callback?.invoke(null) callback?.invoke(null)
} }
}
/**
* Return the current location of the user
*/
fun findCurrentLocation(callback: ((location: android.location.Location?) -> Unit)?) {
val fusedLocationClient: FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context)
if (ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
fusedLocationClient.lastLocation.addOnSuccessListener { location: android.location.Location? ->
// Got last known location. In some rare situations this can be null.
location?.let { currentLocation ->
callback?.invoke(currentLocation)
} ?: run {
// If the current location is null, return null
callback?.invoke(null)
}
}.addOnCanceledListener {
// If there was a problem during the call to last location, return null
callback?.invoke(null)
}
} else {
callback?.invoke(null)
}
} }
} }
Loading…
Cancel
Save