Get last known location (ACCESS_COARSE_LOCATION + no google services)

Viewed 87

Is it possible to get the last known location like google services FusedLocationClient does do it with ACCESS_COARSE_LOCATION permissions only but without google services?

I tried following:

val pm = context.packageManager
val hasFeatureLocation = pm.hasSystemFeature(PackageManager.FEATURE_LOCATION)
var location: Location? = null
if (hasFeatureLocation) {
    val locationManager = context.getSystemService(LOCATION_SERVICE) as LocationManager
    val features = listOf(
        PackageManager.FEATURE_LOCATION_GPS,
        PackageManager.FEATURE_LOCATION_NETWORK
    )
    for (f in features){
        val hasFeature = pm.hasSystemFeature(f)
        if (hasFeature) {
            //val isEnabled = locationManager.isProviderEnabled(f)
            location = locationManager.getLastKnownLocation(f)
        }
        if (location != null)
            break
    }
}

// this would work but needs google services
// val fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)
// location = fusedLocationClient.lastLocation.await<Location?>()

But this fails with java.lang.SecurityException: "android.hardware.location.gps" location provider requires ACCESS_FINE_LOCATION permission..

What I want:

  • I want to use ACCESS_COARSE_LOCATION only (no ACCESS_FINE_LOCATION)
  • I don't want to use googles FusedLocationClient as I don't want to add this dependency for this single task only
  • I only need the approx. GPS location, just what is appropriate for the ACCESS_COARSE_LOCATION permission

I only need the approx. location to show the local weather to the user. Googles FusedLocationClient can do this with the limited ACCESS_COARSE_LOCATION permission, is this possible without the google service as well? Any ideas?

0 Answers
Related