From 80d1077dabec3d9f75f02e9667a3782d8fc99ebc Mon Sep 17 00:00:00 2001 From: Azuo Date: Thu, 12 Aug 2021 14:12:30 +0800 Subject: [PATCH] Make LocationService work in case GMS is not available. --- .../anotherwidget/services/LocationService.kt | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/com/tommasoberlose/anotherwidget/services/LocationService.kt b/app/src/main/java/com/tommasoberlose/anotherwidget/services/LocationService.kt index 906b438..8fd9bcb 100644 --- a/app/src/main/java/com/tommasoberlose/anotherwidget/services/LocationService.kt +++ b/app/src/main/java/com/tommasoberlose/anotherwidget/services/LocationService.kt @@ -42,7 +42,27 @@ class LocationService : Service() { Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED ) { - LocationServices.getFusedLocationProviderClient(this@LocationService).lastLocation.addOnCompleteListener { task -> + if (com.google.android.gms.common.GoogleApiAvailability.getInstance() + .isGooglePlayServicesAvailable(this@LocationService) + == com.google.android.gms.common.ConnectionResult.SUCCESS + ) { + LocationServices.getFusedLocationProviderClient(this@LocationService).lastLocation + } else { + val lm = getSystemService(LOCATION_SERVICE) as android.location.LocationManager + var location: android.location.Location? = null + for (provider in arrayOf( + "fused", // LocationManager.FUSED_PROVIDER, + android.location.LocationManager.GPS_PROVIDER, + android.location.LocationManager.NETWORK_PROVIDER, + android.location.LocationManager.PASSIVE_PROVIDER + )) { + if (lm.isProviderEnabled(provider)) { + location = lm.getLastKnownLocation(provider); + if (location != null) break + } + } + com.google.android.gms.tasks.Tasks.forResult(location) + }.addOnCompleteListener { task -> val networkApi = WeatherNetworkApi(this@LocationService) if (task.isSuccessful) { val location = task.result