From b8e2bf88132716bc3b52c0ae13fb169e1e411eaa Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Fri, 20 Nov 2026 23:29:59 +0100 Subject: [PATCH] platform_location: keep deniedForever, race fixes checkPermission now reports deniedForever after a past request (prefs flag + no rationale), so an app's resume re-check keeps the state. currentLocation asks every enabled provider at once: fused alone sat out its 30 s timeout on the emulator while GPS had a fix. Co-Authored-By: Claude Opus 5.5 --- platform_location/README.md | 8 +- .../dev/kuhy/platform_location/FixStream.kt | 8 +- .../dev/kuhy/platform_location/Locations.kt | 60 +++++++++ .../PlatformLocationPlugin.kt | 115 ++++++++---------- platform_location/lib/platform_location.dart | 6 +- 5 files changed, 122 insertions(+), 75 deletions(-) create mode 100644 platform_location/android/src/main/kotlin/dev/kuhy/platform_location/Locations.kt diff --git a/platform_location/README.md b/platform_location/README.md index 032607e..49a4fd3 100644 --- a/platform_location/README.md +++ b/platform_location/README.md @@ -37,9 +37,11 @@ final fix = await loc.currentLocation(); // throws PlatformException final sub = loc.fixes(interval: const Duration(seconds: 2)).listen((f) {}); ``` -- `checkPermission` reports `granted` or `denied`. Android only tells a - permanent refusal apart right after a request, so `deniedForever` comes - from `requestPermission` (refused and no rationale to show). +- `deniedForever`: refused and Android shows no rationale any more. A + request reports it directly; `checkPermission` reports it only after this + app has asked before (a prefs flag) and only with a foreground Activity, + so an app's resume re-check keeps the state. Background engines see + `denied`. - Provider: GPS when fine location is granted and GPS is on; else the platform fused provider (Android 12+, AOSP), else network. No Play services fused provider. diff --git a/platform_location/android/src/main/kotlin/dev/kuhy/platform_location/FixStream.kt b/platform_location/android/src/main/kotlin/dev/kuhy/platform_location/FixStream.kt index f48aefe..cb4eeb6 100644 --- a/platform_location/android/src/main/kotlin/dev/kuhy/platform_location/FixStream.kt +++ b/platform_location/android/src/main/kotlin/dev/kuhy/platform_location/FixStream.kt @@ -21,8 +21,8 @@ internal class FixStream(private val ctx: Context) : EventChannel.StreamHandler stop() val intervalMs = ((arguments as? Map<*, *>)?.get("intervalMs") as? Number) ?.toLong() ?: DEFAULT_INTERVAL_MS - val lm = PlatformLocationPlugin.locationManager(ctx) - val provider = PlatformLocationPlugin.pickProvider(ctx, lm) + val lm = Locations.locationManager(ctx) + val provider = Locations.pickProvider(ctx, lm) ?: return sink.error("unavailable", "no permission or provider", null) val request = LocationRequestCompat.Builder(intervalMs) .setQuality(LocationRequestCompat.QUALITY_HIGH_ACCURACY) @@ -30,7 +30,7 @@ internal class FixStream(private val ctx: Context) : EventChannel.StreamHandler .build() val l = object : LocationListenerCompat { override fun onLocationChanged(location: Location) { - sink.success(PlatformLocationPlugin.toMap(location)) + sink.success(Locations.toMap(location)) } override fun onProviderDisabled(disabled: String) { @@ -58,7 +58,7 @@ internal class FixStream(private val ctx: Context) : EventChannel.StreamHandler private fun stop() { val l = listener ?: return listener = null - LocationManagerCompat.removeUpdates(PlatformLocationPlugin.locationManager(ctx), l) + LocationManagerCompat.removeUpdates(Locations.locationManager(ctx), l) } private companion object { diff --git a/platform_location/android/src/main/kotlin/dev/kuhy/platform_location/Locations.kt b/platform_location/android/src/main/kotlin/dev/kuhy/platform_location/Locations.kt new file mode 100644 index 0000000..709dac5 --- /dev/null +++ b/platform_location/android/src/main/kotlin/dev/kuhy/platform_location/Locations.kt @@ -0,0 +1,60 @@ +package dev.kuhy.platform_location + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import android.location.Location +import android.location.LocationManager +import android.os.Build +import androidx.core.content.ContextCompat +import androidx.core.location.LocationCompat +import androidx.core.location.LocationManagerCompat + +/** Permission, provider and fix helpers shared by the plugin and [FixStream]. */ +internal object Locations { + fun locationManager(ctx: Context): LocationManager = + ctx.getSystemService(Context.LOCATION_SERVICE) as LocationManager + + fun locationEnabled(ctx: Context): Boolean = + LocationManagerCompat.isLocationEnabled(locationManager(ctx)) + + fun hasFine(ctx: Context): Boolean = ContextCompat.checkSelfPermission( + ctx, + Manifest.permission.ACCESS_FINE_LOCATION, + ) == PackageManager.PERMISSION_GRANTED + + fun hasAny(ctx: Context): Boolean = hasFine(ctx) || + ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_COARSE_LOCATION) == + PackageManager.PERMISSION_GRANTED + + /** + * Enabled providers, best first: GPS when fine location is granted, then + * the platform fused provider (AOSP, Android 12+), network, and GPS for a + * coarse-only app (Android 12+ coarsens it). Empty without permission. + */ + fun candidates(ctx: Context, lm: LocationManager): List { + if (!hasAny(ctx)) return emptyList() + val enabled = lm.getProviders(true) + return buildList { + if (hasFine(ctx)) add(LocationManager.GPS_PROVIDER) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + add(LocationManager.FUSED_PROVIDER) + } + add(LocationManager.NETWORK_PROVIDER) + add(LocationManager.GPS_PROVIDER) + }.distinct().filter { it in enabled } + } + + /** The provider a fix stream uses; null when none fits. */ + fun pickProvider(ctx: Context, lm: LocationManager): String? = + candidates(ctx, lm).firstOrNull() + + fun toMap(l: Location): Map = mapOf( + "time" to l.time, + "latitude" to l.latitude, + "longitude" to l.longitude, + "altitude" to if (l.hasAltitude()) l.altitude else 0.0, + "accuracy" to if (l.hasAccuracy()) l.accuracy.toDouble() else 0.0, + "isMock" to LocationCompat.isMock(l), + ) +} diff --git a/platform_location/android/src/main/kotlin/dev/kuhy/platform_location/PlatformLocationPlugin.kt b/platform_location/android/src/main/kotlin/dev/kuhy/platform_location/PlatformLocationPlugin.kt index 7c2eca0..01d176d 100644 --- a/platform_location/android/src/main/kotlin/dev/kuhy/platform_location/PlatformLocationPlugin.kt +++ b/platform_location/android/src/main/kotlin/dev/kuhy/platform_location/PlatformLocationPlugin.kt @@ -6,10 +6,8 @@ import android.content.Context import android.content.pm.PackageManager import android.location.Location import android.location.LocationManager -import android.os.Build import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat -import androidx.core.location.LocationCompat import androidx.core.location.LocationManagerCompat import androidx.core.os.CancellationSignal import io.flutter.embedding.engine.plugins.FlutterPlugin @@ -88,9 +86,8 @@ class PlatformLocationPlugin : override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { val ctx = context ?: return result.error("no_context", "detached", null) when (call.method) { - "isLocationEnabled" -> result.success(locationEnabled(ctx)) - "checkPermission" -> - result.success(if (hasAny(ctx)) GRANTED else DENIED) + "isLocationEnabled" -> result.success(Locations.locationEnabled(ctx)) + "checkPermission" -> result.success(check(ctx)) "requestPermission" -> request(ctx, call.argument("precise") ?: true, result) "currentLocation" -> current(ctx, result) @@ -98,14 +95,32 @@ class PlatformLocationPlugin : } } + /** + * Granted, or a refusal. "Forever" needs a past request (remembered in + * prefs) plus an Activity to ask for the rationale: without the memory, + * the app's resume re-check would turn a fresh deniedForever back into + * denied. Same rule geolocator used. + */ + private fun check(ctx: Context): String { + if (Locations.hasAny(ctx)) return GRANTED + val activity = binding?.activity ?: return DENIED + return if (asked(ctx) && permanentlyDenied(activity)) DENIED_FOREVER else DENIED + } + + private fun prefs(ctx: Context) = + ctx.getSharedPreferences("dev.kuhy.platform_location", Context.MODE_PRIVATE) + + private fun asked(ctx: Context): Boolean = prefs(ctx).getBoolean(ASKED, false) + private fun request(ctx: Context, precise: Boolean, result: MethodChannel.Result) { - if (hasAny(ctx)) return result.success(GRANTED) + if (Locations.hasAny(ctx)) return result.success(GRANTED) val activity = binding?.activity ?: return result.error("no_activity", "no foreground activity", null) if (pendingPermission != null) { return result.error("busy", "a permission request is in flight", null) } pendingPermission = result + prefs(ctx).edit().putBoolean(ASKED, true).apply() val perms = if (precise) { arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, COARSE) } else { @@ -139,38 +154,50 @@ class PlatformLocationPlugin : private fun permanentlyDenied(activity: Activity): Boolean = !ActivityCompat.shouldShowRequestPermissionRationale(activity, COARSE) + /** + * Asks every enabled provider at once; the first fix wins and cancels + * the rest. One provider alone can sit out its whole ~30 s timeout with + * nothing (seen: fused indoors while GPS had a fix). When all come back + * empty, the newest cached fix, else a no_fix error. + */ private fun current(ctx: Context, result: MethodChannel.Result) { - val lm = locationManager(ctx) - val provider = pickProvider(ctx, lm) - ?: return result.error("unavailable", "no permission or provider", null) + val lm = Locations.locationManager(ctx) + val providers = Locations.candidates(ctx, lm) + if (providers.isEmpty()) { + return result.error("unavailable", "no permission or provider", null) + } + val cancel = providers.associateWith { CancellationSignal() } + var pending = providers.size var answered = false val reply = { location: Location? -> - if (!answered) { + pending-- + if (!answered && (location != null || pending == 0)) { answered = true + cancel.values.forEach { it.cancel() } val fix = location ?: lastKnown(lm, ctx) if (fix == null) { - result.error("no_fix", "no location from $provider", null) + result.error("no_fix", "no location from $providers", null) } else { - result.success(toMap(fix)) + result.success(Locations.toMap(fix)) } } } - try { - LocationManagerCompat.getCurrentLocation( - lm, - provider, - CancellationSignal(), - ContextCompat.getMainExecutor(ctx), - ) { reply(it) } - } catch (e: SecurityException) { - result.error("denied", e.message, null) + val main = ContextCompat.getMainExecutor(ctx) + for (provider in providers) { + try { + LocationManagerCompat.getCurrentLocation( + lm, provider, cancel.getValue(provider), main, + ) { reply(it) } + } catch (_: SecurityException) { + main.execute { reply(null) } + } } } // A one-shot request can time out indoors; the newest cached fix from // any enabled provider is good enough for a coarse "where am I". private fun lastKnown(lm: LocationManager, ctx: Context): Location? { - if (!hasAny(ctx)) return null + if (!Locations.hasAny(ctx)) return null return try { lm.getProviders(true) .mapNotNull { lm.getLastKnownLocation(it) } @@ -187,48 +214,6 @@ class PlatformLocationPlugin : private const val GRANTED = "granted" private const val DENIED = "denied" private const val DENIED_FOREVER = "deniedForever" - - fun locationManager(ctx: Context): LocationManager = - ctx.getSystemService(Context.LOCATION_SERVICE) as LocationManager - - fun locationEnabled(ctx: Context): Boolean = - LocationManagerCompat.isLocationEnabled(locationManager(ctx)) - - fun hasFine(ctx: Context): Boolean = ContextCompat.checkSelfPermission( - ctx, - Manifest.permission.ACCESS_FINE_LOCATION, - ) == PackageManager.PERMISSION_GRANTED - - fun hasAny(ctx: Context): Boolean = hasFine(ctx) || - ContextCompat.checkSelfPermission(ctx, COARSE) == - PackageManager.PERMISSION_GRANTED - - /** - * GPS when fine location is granted and GPS is on; otherwise the - * platform fused provider (AOSP, Android 12+) or the network one. - * Null when no permission or no enabled provider fits. - */ - fun pickProvider(ctx: Context, lm: LocationManager): String? { - if (!hasAny(ctx)) return null - val enabled = lm.getProviders(true) - val order = buildList { - if (hasFine(ctx)) add(LocationManager.GPS_PROVIDER) - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { - add(LocationManager.FUSED_PROVIDER) - } - add(LocationManager.NETWORK_PROVIDER) - add(LocationManager.GPS_PROVIDER) - } - return order.firstOrNull { it in enabled } - } - - fun toMap(l: Location): Map = mapOf( - "time" to l.time, - "latitude" to l.latitude, - "longitude" to l.longitude, - "altitude" to if (l.hasAltitude()) l.altitude else 0.0, - "accuracy" to if (l.hasAccuracy()) l.accuracy.toDouble() else 0.0, - "isMock" to LocationCompat.isMock(l), - ) + private const val ASKED = "asked" } } diff --git a/platform_location/lib/platform_location.dart b/platform_location/lib/platform_location.dart index 01b24df..e0005e4 100644 --- a/platform_location/lib/platform_location.dart +++ b/platform_location/lib/platform_location.dart @@ -93,9 +93,9 @@ abstract class PlatformLocation { /// Whether the device's location switch is on. Future isLocationEnabled(); - /// The permission as it stands; never prompts. Reports - /// [LocationPermissionState.denied], never `deniedForever`: Android only - /// tells a permanent refusal apart right after a request. + /// The permission as it stands; never prompts. `deniedForever` only once + /// this app has asked before and a foreground Activity shows no rationale + /// (the rule geolocator used); a background engine sees `denied`. Future checkPermission(); /// Shows the system prompt (needs a foreground Activity). [precise] asks