Skip to content

Commit

Permalink
use latch
Browse files Browse the repository at this point in the history
  • Loading branch information
jonesmac committed Nov 8, 2024
1 parent b3f571f commit 46b5ed0
Showing 1 changed file with 42 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import com.google.android.gms.location.LocationServices
import com.squareup.moshi.JsonClass
import network.xyo.client.payload.XyoPayload
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit

data class Coordinates(
val accuracy: Float?,
Expand Down Expand Up @@ -38,7 +39,10 @@ class XyoLocationPayload (
companion object {

fun detect(context: Context): XyoLocationPayload? {
if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) != 1) {
val gpInstance = GoogleApiAvailability.getInstance()
val available = gpInstance.isGooglePlayServicesAvailable(context)
val googlePlayServicesAvailable = available == 1
if (googlePlayServicesAvailable) {
Log.e("xyoClient", "Google Play Service not installed")
return null
}
Expand All @@ -57,34 +61,47 @@ class XyoLocationPayload (

val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
var coordinates: Coordinates? = null
val latch = CountDownLatch(1)

fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
if (location != null) {
coordinates = Coordinates(
location.accuracy,
location.altitude,
null,
location.bearing,
location.latitude,
location.longitude,
location.speed
)
// countDown to zero to lift the latch
latch.countDown()
} else {
// countDown to zero to lift the latch
latch.countDown()
Log.e("xyoClient","Location not available")
try {
val latch = CountDownLatch(1)

fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
if (location != null) {
coordinates = Coordinates(
location.accuracy,
location.altitude,
null,
location.bearing,
location.latitude,
location.longitude,
location.speed
)
// countDown to zero to lift the latch
latch.countDown()
} else {
// countDown to zero to lift the latch
latch.countDown()
Log.e("xyoClient","Location not available")
}
}
.addOnFailureListener {
Log.e("xyoClient","Failed to get location: ${it.message}")
}
// Wait for up to 5 seconds for the location
latch.await(5, TimeUnit.SECONDS)

if (coordinates == null) {
return null
} else {
val currentLocation = CurrentLocation(coordinates!!, System.currentTimeMillis())
return XyoLocationPayload(currentLocation)
}
.addOnFailureListener {
Log.e("xyoClient","Failed to get location: ${it.message}")
}
} catch (e: InterruptedException) {
e.printStackTrace()
}
return null

val currentLocation = CurrentLocation(coordinates!!, System.currentTimeMillis())
return XyoLocationPayload(currentLocation)
}
}
}

0 comments on commit 46b5ed0

Please sign in to comment.