Skip to content

Commit

Permalink
Fall back to the old fashioned GPS provided when Play Services are ab…
Browse files Browse the repository at this point in the history
…sent
  • Loading branch information
cristan committed Dec 17, 2024
1 parent df10ccd commit df2a39b
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions app/src/main/java/nl/ovfietsbeschikbaarheid/util/LocationLoader.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,22 @@ package nl.ovfietsbeschikbaarheid.util

import android.annotation.SuppressLint
import android.content.Context
import android.content.Context.LOCATION_SERVICE
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.location.CurrentLocationRequest
import com.google.android.gms.location.Granularity
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.Priority
import com.google.android.gms.tasks.CancellationTokenSource
import dev.jordond.compass.Coordinates
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.tasks.await
import kotlin.coroutines.resume

class LocationLoader(
private val context: Context
Expand All @@ -20,6 +28,12 @@ class LocationLoader(

@SuppressLint("MissingPermission")
suspend fun loadCurrentCoordinates(): Coordinates? {
val playServicesAvailable = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context)
if (playServicesAvailable != ConnectionResult.SUCCESS) {
val locationService = context.getSystemService(LOCATION_SERVICE) as LocationManager
return locationService.awaitCurrentLocation()?.toCoordinates()
}

val currentLocationRequest = CurrentLocationRequest.Builder()
.setDurationMillis(5000)
.setGranularity(Granularity.GRANULARITY_COARSE)
Expand All @@ -39,4 +53,31 @@ class LocationLoader(
}
}

@SuppressLint("MissingPermission")
private suspend fun LocationManager.awaitCurrentLocation(): Location? {
return suspendCancellableCoroutine { continuation ->
val provider = LocationManager.GPS_PROVIDER

val locationListener = object : LocationListener {
override fun onLocationChanged(location: Location) {
continuation.resume(location)
}

@Deprecated("Deprecated in Java")
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) = Unit
override fun onProviderEnabled(provider: String) = Unit
override fun onProviderDisabled(provider: String) {
continuation.resume(null) // Provider was disabled, return null
}
}

@Suppress("DEPRECATION")
requestSingleUpdate(provider, locationListener, null)

continuation.invokeOnCancellation {
removeUpdates(locationListener)
}
}
}

private fun Location.toCoordinates() = Coordinates(latitude, longitude)

0 comments on commit df2a39b

Please sign in to comment.