platform_location: keep deniedForever, race fixes
Some checks are pending
file length / file-length (push) Waiting to run
kuhy_credit drift / drift (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
platform_location tests / test (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run

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 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-20 23:29:59 +01:00
parent 44ed951630
commit b8e2bf8813
5 changed files with 122 additions and 75 deletions

View File

@ -37,9 +37,11 @@ final fix = await loc.currentLocation(); // throws PlatformException
final sub = loc.fixes(interval: const Duration(seconds: 2)).listen((f) {}); final sub = loc.fixes(interval: const Duration(seconds: 2)).listen((f) {});
``` ```
- `checkPermission` reports `granted` or `denied`. Android only tells a - `deniedForever`: refused and Android shows no rationale any more. A
permanent refusal apart right after a request, so `deniedForever` comes request reports it directly; `checkPermission` reports it only after this
from `requestPermission` (refused and no rationale to show). 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 - Provider: GPS when fine location is granted and GPS is on; else the
platform fused provider (Android 12+, AOSP), else network. No Play platform fused provider (Android 12+, AOSP), else network. No Play
services fused provider. services fused provider.

View File

@ -21,8 +21,8 @@ internal class FixStream(private val ctx: Context) : EventChannel.StreamHandler
stop() stop()
val intervalMs = ((arguments as? Map<*, *>)?.get("intervalMs") as? Number) val intervalMs = ((arguments as? Map<*, *>)?.get("intervalMs") as? Number)
?.toLong() ?: DEFAULT_INTERVAL_MS ?.toLong() ?: DEFAULT_INTERVAL_MS
val lm = PlatformLocationPlugin.locationManager(ctx) val lm = Locations.locationManager(ctx)
val provider = PlatformLocationPlugin.pickProvider(ctx, lm) val provider = Locations.pickProvider(ctx, lm)
?: return sink.error("unavailable", "no permission or provider", null) ?: return sink.error("unavailable", "no permission or provider", null)
val request = LocationRequestCompat.Builder(intervalMs) val request = LocationRequestCompat.Builder(intervalMs)
.setQuality(LocationRequestCompat.QUALITY_HIGH_ACCURACY) .setQuality(LocationRequestCompat.QUALITY_HIGH_ACCURACY)
@ -30,7 +30,7 @@ internal class FixStream(private val ctx: Context) : EventChannel.StreamHandler
.build() .build()
val l = object : LocationListenerCompat { val l = object : LocationListenerCompat {
override fun onLocationChanged(location: Location) { override fun onLocationChanged(location: Location) {
sink.success(PlatformLocationPlugin.toMap(location)) sink.success(Locations.toMap(location))
} }
override fun onProviderDisabled(disabled: String) { override fun onProviderDisabled(disabled: String) {
@ -58,7 +58,7 @@ internal class FixStream(private val ctx: Context) : EventChannel.StreamHandler
private fun stop() { private fun stop() {
val l = listener ?: return val l = listener ?: return
listener = null listener = null
LocationManagerCompat.removeUpdates(PlatformLocationPlugin.locationManager(ctx), l) LocationManagerCompat.removeUpdates(Locations.locationManager(ctx), l)
} }
private companion object { private companion object {

View File

@ -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<String> {
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<String, Any> = 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),
)
}

View File

@ -6,10 +6,8 @@ import android.content.Context
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.location.Location import android.location.Location
import android.location.LocationManager import android.location.LocationManager
import android.os.Build
import androidx.core.app.ActivityCompat import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import androidx.core.location.LocationCompat
import androidx.core.location.LocationManagerCompat import androidx.core.location.LocationManagerCompat
import androidx.core.os.CancellationSignal import androidx.core.os.CancellationSignal
import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.FlutterPlugin
@ -88,9 +86,8 @@ class PlatformLocationPlugin :
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
val ctx = context ?: return result.error("no_context", "detached", null) val ctx = context ?: return result.error("no_context", "detached", null)
when (call.method) { when (call.method) {
"isLocationEnabled" -> result.success(locationEnabled(ctx)) "isLocationEnabled" -> result.success(Locations.locationEnabled(ctx))
"checkPermission" -> "checkPermission" -> result.success(check(ctx))
result.success(if (hasAny(ctx)) GRANTED else DENIED)
"requestPermission" -> "requestPermission" ->
request(ctx, call.argument<Boolean>("precise") ?: true, result) request(ctx, call.argument<Boolean>("precise") ?: true, result)
"currentLocation" -> current(ctx, 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) { 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 val activity = binding?.activity
?: return result.error("no_activity", "no foreground activity", null) ?: return result.error("no_activity", "no foreground activity", null)
if (pendingPermission != null) { if (pendingPermission != null) {
return result.error("busy", "a permission request is in flight", null) return result.error("busy", "a permission request is in flight", null)
} }
pendingPermission = result pendingPermission = result
prefs(ctx).edit().putBoolean(ASKED, true).apply()
val perms = if (precise) { val perms = if (precise) {
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, COARSE) arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, COARSE)
} else { } else {
@ -139,38 +154,50 @@ class PlatformLocationPlugin :
private fun permanentlyDenied(activity: Activity): Boolean = private fun permanentlyDenied(activity: Activity): Boolean =
!ActivityCompat.shouldShowRequestPermissionRationale(activity, COARSE) !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) { private fun current(ctx: Context, result: MethodChannel.Result) {
val lm = locationManager(ctx) val lm = Locations.locationManager(ctx)
val provider = pickProvider(ctx, lm) val providers = Locations.candidates(ctx, lm)
?: return result.error("unavailable", "no permission or provider", null) if (providers.isEmpty()) {
return result.error("unavailable", "no permission or provider", null)
}
val cancel = providers.associateWith { CancellationSignal() }
var pending = providers.size
var answered = false var answered = false
val reply = { location: Location? -> val reply = { location: Location? ->
if (!answered) { pending--
if (!answered && (location != null || pending == 0)) {
answered = true answered = true
cancel.values.forEach { it.cancel() }
val fix = location ?: lastKnown(lm, ctx) val fix = location ?: lastKnown(lm, ctx)
if (fix == null) { if (fix == null) {
result.error("no_fix", "no location from $provider", null) result.error("no_fix", "no location from $providers", null)
} else { } else {
result.success(toMap(fix)) result.success(Locations.toMap(fix))
} }
} }
} }
try { val main = ContextCompat.getMainExecutor(ctx)
LocationManagerCompat.getCurrentLocation( for (provider in providers) {
lm, try {
provider, LocationManagerCompat.getCurrentLocation(
CancellationSignal(), lm, provider, cancel.getValue(provider), main,
ContextCompat.getMainExecutor(ctx), ) { reply(it) }
) { reply(it) } } catch (_: SecurityException) {
} catch (e: SecurityException) { main.execute { reply(null) }
result.error("denied", e.message, null) }
} }
} }
// A one-shot request can time out indoors; the newest cached fix from // 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". // any enabled provider is good enough for a coarse "where am I".
private fun lastKnown(lm: LocationManager, ctx: Context): Location? { private fun lastKnown(lm: LocationManager, ctx: Context): Location? {
if (!hasAny(ctx)) return null if (!Locations.hasAny(ctx)) return null
return try { return try {
lm.getProviders(true) lm.getProviders(true)
.mapNotNull { lm.getLastKnownLocation(it) } .mapNotNull { lm.getLastKnownLocation(it) }
@ -187,48 +214,6 @@ class PlatformLocationPlugin :
private const val GRANTED = "granted" private const val GRANTED = "granted"
private const val DENIED = "denied" private const val DENIED = "denied"
private const val DENIED_FOREVER = "deniedForever" private const val DENIED_FOREVER = "deniedForever"
private const val ASKED = "asked"
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<String, Any> = 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),
)
} }
} }

View File

@ -93,9 +93,9 @@ abstract class PlatformLocation {
/// Whether the device's location switch is on. /// Whether the device's location switch is on.
Future<bool> isLocationEnabled(); Future<bool> isLocationEnabled();
/// The permission as it stands; never prompts. Reports /// The permission as it stands; never prompts. `deniedForever` only once
/// [LocationPermissionState.denied], never `deniedForever`: Android only /// this app has asked before and a foreground Activity shows no rationale
/// tells a permanent refusal apart right after a request. /// (the rule geolocator used); a background engine sees `denied`.
Future<LocationPermissionState> checkPermission(); Future<LocationPermissionState> checkPermission();
/// Shows the system prompt (needs a foreground Activity). [precise] asks /// Shows the system prompt (needs a foreground Activity). [precise] asks