diff --git a/.github/workflows/platform-location-tests.yml b/.github/workflows/platform-location-tests.yml
new file mode 100644
index 0000000..5beab42
--- /dev/null
+++ b/.github/workflows/platform-location-tests.yml
@@ -0,0 +1,36 @@
+name: platform_location tests
+
+on:
+ push:
+ branches: [main]
+ paths: ['platform_location/**']
+ pull_request:
+ branches: [main]
+ paths: ['platform_location/**']
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ defaults:
+ run:
+ working-directory: platform_location
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Flutter
+ uses: subosito/flutter-action@v2
+ with:
+ channel: stable
+
+ - name: Install dependencies
+ run: flutter pub get
+
+ - name: Analyze
+ run: flutter analyze
+
+ - name: Run tests with coverage
+ run: flutter test --coverage
+
+ - name: Enforce 100% line coverage
+ run: scripts/check_coverage.sh coverage/lcov.info 100
diff --git a/README.md b/README.md
index 6fce3fc..a7673e4 100644
--- a/README.md
+++ b/README.md
@@ -57,6 +57,23 @@ dependencies:
path: google_account_token
```
+## platform_location/
+
+Flutter plugin (Android only): location through AOSP `LocationManager`
+(androidx `LocationManagerCompat`), replacing `geolocator`, whose Android
+side links non-free `play-services-location`. Used by umbrella and
+workout_app.
+
+Consume via:
+```yaml
+dependencies:
+ platform_location:
+ git:
+ url: https://github.com/kuhyx/utils
+ ref: platform_location-v0.1.0
+ path: platform_location
+```
+
## crdt-sync/
Python CRDT sync library (package: `crdt_sync`, not published to PyPI). Same
diff --git a/platform_location/.gitignore b/platform_location/.gitignore
new file mode 100644
index 0000000..fd5818f
--- /dev/null
+++ b/platform_location/.gitignore
@@ -0,0 +1,7 @@
+.dart_tool/
+.packages
+build/
+pubspec.lock
+coverage/
+*.iml
+pubspec_overrides.yaml
diff --git a/platform_location/.pre-commit-config.yaml b/platform_location/.pre-commit-config.yaml
new file mode 100644
index 0000000..15a3f2c
--- /dev/null
+++ b/platform_location/.pre-commit-config.yaml
@@ -0,0 +1,61 @@
+# Pre-commit Configuration for platform_location
+# Install: pre-commit install && pre-commit install --hook-type pre-push
+# Run: pre-commit run --all-files
+
+# NOTE: this subproject lives inside the ~/src/utils monorepo, whose git root is
+# one level up. pre-commit always runs hooks from the git root, so every path
+# below is written relative to THAT, not to this directory, and the top-level
+# `files` key keeps these hooks off the sibling subprojects. CI invokes this
+# config exactly the same way:
+# pre-commit run --config platform_location/.pre-commit-config.yaml --all-files
+files: ^platform_location/
+
+default_stages: [pre-commit]
+fail_fast: false
+
+repos:
+ - repo: https://github.com/pre-commit/pre-commit-hooks
+ rev: v4.6.0
+ hooks:
+ - id: trailing-whitespace
+ args: [--markdown-linebreak-ext=md]
+ - id: end-of-file-fixer
+ - id: check-yaml
+ - id: check-merge-conflict
+ - id: mixed-line-ending
+ args: [--fix=lf]
+
+ - repo: local
+ hooks:
+ - id: file-length-cap
+ name: file length <= 250 lines
+ entry: bash scripts/check_file_length.sh
+ language: system
+ pass_filenames: true
+ - id: subproject-scope
+ name: subproject scope regex still matches
+ entry: scripts/check_subproject_scope.sh platform_location
+ language: script
+ # always_run so the top-level `files` filter cannot skip the one hook
+ # whose job is to notice that filter has stopped matching anything.
+ always_run: true
+ pass_filenames: false
+ - id: dart-format
+ name: dart format --set-exit-if-changed
+ entry: bash -c 'cd platform_location && dart format --set-exit-if-changed lib test'
+ language: system
+ pass_filenames: false
+ - id: flutter-analyze
+ name: flutter analyze
+ entry: bash -c 'cd platform_location && flutter analyze'
+ language: system
+ pass_filenames: false
+ - id: flutter-test-coverage
+ name: flutter test --coverage with 100% line-coverage gate
+ entry: >-
+ bash -c 'cd platform_location && flutter test --coverage &&
+ scripts/check_coverage.sh coverage/lcov.info 100'
+ language: system
+ pass_filenames: false
+ require_serial: true
+ stages: [pre-push]
diff --git a/platform_location/README.md b/platform_location/README.md
new file mode 100644
index 0000000..032607e
--- /dev/null
+++ b/platform_location/README.md
@@ -0,0 +1,51 @@
+# platform_location
+
+Android location through AOSP's `LocationManager` (androidx
+`LocationManagerCompat`, Apache-2.0), owned once for every app. It replaces
+`geolocator`: `geolocator_android` links
+`com.google.android.gms:play-services-location` (plus play-services-base,
+-basement and -tasks, all non-free) even with `forceLocationManager: true`.
+An APK built with this package has no `com/google/android/gms` classes.
+
+## Install
+
+```yaml
+dependencies:
+ platform_location:
+ git:
+ url: https://github.com/kuhyx/utils
+ ref: platform_location-v0.1.0
+ path: platform_location
+```
+
+Android plugins auto-register, in the UI engine and in background engines
+(a flutter_foreground_task service isolate) alike. The app declares
+`ACCESS_COARSE_LOCATION` and, for GPS precision, `ACCESS_FINE_LOCATION`.
+
+## API
+
+```dart
+import 'package:platform_location/platform_location.dart';
+
+final loc = PlatformLocation.instance;
+if (!await loc.isLocationEnabled()) { /* switch is off */ }
+var perm = await loc.checkPermission(); // never prompts
+if (perm != LocationPermissionState.granted) {
+ perm = await loc.requestPermission(precise: false); // needs an Activity
+}
+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).
+- 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.
+- `currentLocation` falls back to the newest last-known fix, then throws
+ `no_fix`. Stream errors: `unavailable`, `denied`, `provider_disabled`.
+- `LocationFix`: `time` (UTC), `latitude`, `longitude`, `altitude` (0 when
+ the provider has none), `accuracy` (m, 0 when unknown), `isMock`.
+
+Tests replace `PlatformLocation.instance` with a fake subclass.
diff --git a/platform_location/analysis_options.yaml b/platform_location/analysis_options.yaml
new file mode 100644
index 0000000..286e24c
--- /dev/null
+++ b/platform_location/analysis_options.yaml
@@ -0,0 +1,38 @@
+include: package:very_good_analysis/analysis_options.yaml
+
+analyzer:
+ language:
+ strict-casts: true
+ strict-inference: true
+ strict-raw-types: true
+ errors:
+ # Promote key lints to errors so they fail CI, not just warn.
+ missing_required_param: error
+ unnecessary_null_comparison: error
+ dead_code: error
+ invalid_annotation_target: error
+ exclude:
+ - build/**
+ - "**/*.g.dart"
+ - "**/*.freezed.dart"
+ - "test/**"
+ - android/**
+ - ios/**
+ - web/**
+ - windows/**
+ - macos/**
+ - linux/**
+
+linter:
+ rules:
+ # very_good_analysis enables most rules; add extras it doesn't include.
+ always_use_package_imports: true
+ avoid_print: true
+ avoid_relative_lib_imports: true
+ cancel_subscriptions: true
+ close_sinks: true
+ comment_references: false # conflicts with typical Flutter API docs style
+ directives_ordering: true
+ lines_longer_than_80_chars: true
+ public_member_api_docs: true
+ unawaited_futures: true
diff --git a/platform_location/android/build.gradle.kts b/platform_location/android/build.gradle.kts
new file mode 100644
index 0000000..038a7f4
--- /dev/null
+++ b/platform_location/android/build.gradle.kts
@@ -0,0 +1,59 @@
+group = "dev.kuhy.platform_location"
+version = "0.1.0"
+
+buildscript {
+ val kotlinVersion = "2.4.0"
+ repositories {
+ google()
+ mavenCentral()
+ }
+
+ dependencies {
+ classpath("com.android.tools.build:gradle:9.5.1")
+ classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
+ }
+}
+
+allprojects {
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+plugins {
+ id("com.android.library")
+}
+
+android {
+ namespace = "dev.kuhy.platform_location"
+
+ compileSdk = 37
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+
+ sourceSets {
+ getByName("main") {
+ java.srcDirs("src/main/kotlin")
+ }
+ }
+
+ defaultConfig {
+ minSdk = 24
+ }
+}
+
+kotlin {
+ compilerOptions {
+ jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
+ }
+}
+
+dependencies {
+ // LocationManagerCompat / LocationRequestCompat / LocationCompat (AOSP,
+ // Apache-2.0). Nothing from com.google.android.gms: that is the point.
+ implementation("androidx.core:core:1.19.1")
+}
diff --git a/platform_location/android/settings.gradle.kts b/platform_location/android/settings.gradle.kts
new file mode 100644
index 0000000..eeb5373
--- /dev/null
+++ b/platform_location/android/settings.gradle.kts
@@ -0,0 +1 @@
+rootProject.name = "platform_location"
diff --git a/platform_location/android/src/main/AndroidManifest.xml b/platform_location/android/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..94cbbcf
--- /dev/null
+++ b/platform_location/android/src/main/AndroidManifest.xml
@@ -0,0 +1 @@
+
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
new file mode 100644
index 0000000..f48aefe
--- /dev/null
+++ b/platform_location/android/src/main/kotlin/dev/kuhy/platform_location/FixStream.kt
@@ -0,0 +1,67 @@
+package dev.kuhy.platform_location
+
+import android.content.Context
+import android.location.Location
+import androidx.core.content.ContextCompat
+import androidx.core.location.LocationListenerCompat
+import androidx.core.location.LocationManagerCompat
+import androidx.core.location.LocationRequestCompat
+import io.flutter.plugin.common.EventChannel
+
+/**
+ * The `dev.kuhy/platform_location/fixes` stream: LocationManager updates on
+ * the main looper, removed on cancel. Errors end the Dart stream's listen
+ * with a PlatformException ("unavailable", "denied", "provider_disabled").
+ */
+internal class FixStream(private val ctx: Context) : EventChannel.StreamHandler {
+
+ private var listener: LocationListenerCompat? = null
+
+ override fun onListen(arguments: Any?, sink: EventChannel.EventSink) {
+ 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)
+ ?: return sink.error("unavailable", "no permission or provider", null)
+ val request = LocationRequestCompat.Builder(intervalMs)
+ .setQuality(LocationRequestCompat.QUALITY_HIGH_ACCURACY)
+ .setMinUpdateIntervalMillis(intervalMs / 2)
+ .build()
+ val l = object : LocationListenerCompat {
+ override fun onLocationChanged(location: Location) {
+ sink.success(PlatformLocationPlugin.toMap(location))
+ }
+
+ override fun onProviderDisabled(disabled: String) {
+ if (disabled == provider) {
+ sink.error("provider_disabled", "$provider was switched off", null)
+ }
+ }
+ }
+ try {
+ LocationManagerCompat.requestLocationUpdates(
+ lm,
+ provider,
+ request,
+ ContextCompat.getMainExecutor(ctx),
+ l,
+ )
+ listener = l
+ } catch (e: SecurityException) {
+ sink.error("denied", e.message, null)
+ }
+ }
+
+ override fun onCancel(arguments: Any?) = stop()
+
+ private fun stop() {
+ val l = listener ?: return
+ listener = null
+ LocationManagerCompat.removeUpdates(PlatformLocationPlugin.locationManager(ctx), l)
+ }
+
+ private companion object {
+ const val DEFAULT_INTERVAL_MS = 2000L
+ }
+}
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
new file mode 100644
index 0000000..7c2eca0
--- /dev/null
+++ b/platform_location/android/src/main/kotlin/dev/kuhy/platform_location/PlatformLocationPlugin.kt
@@ -0,0 +1,234 @@
+package dev.kuhy.platform_location
+
+import android.Manifest
+import android.app.Activity
+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
+import io.flutter.embedding.engine.plugins.activity.ActivityAware
+import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
+import io.flutter.plugin.common.EventChannel
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+import io.flutter.plugin.common.PluginRegistry
+
+/**
+ * Location through AOSP's LocationManager (androidx LocationManagerCompat).
+ * No Google Play services. The Dart side is `lib/platform_location.dart`.
+ *
+ * Only requestPermission needs an Activity; everything else works in a
+ * background engine (foreground-service isolate) too.
+ */
+class PlatformLocationPlugin :
+ FlutterPlugin,
+ ActivityAware,
+ MethodChannel.MethodCallHandler,
+ PluginRegistry.RequestPermissionsResultListener {
+
+ private var context: Context? = null
+ private var channel: MethodChannel? = null
+ private var events: EventChannel? = null
+ private var fixStream: FixStream? = null
+ private var binding: ActivityPluginBinding? = null
+ private var pendingPermission: MethodChannel.Result? = null
+
+ override fun onAttachedToEngine(flutter: FlutterPlugin.FlutterPluginBinding) {
+ val ctx = flutter.applicationContext
+ context = ctx
+ channel = MethodChannel(flutter.binaryMessenger, CHANNEL).also {
+ it.setMethodCallHandler(this)
+ }
+ val stream = FixStream(ctx)
+ fixStream = stream
+ events = EventChannel(flutter.binaryMessenger, "$CHANNEL/fixes").also {
+ it.setStreamHandler(stream)
+ }
+ }
+
+ override fun onDetachedFromEngine(flutter: FlutterPlugin.FlutterPluginBinding) {
+ channel?.setMethodCallHandler(null)
+ events?.setStreamHandler(null)
+ fixStream?.onCancel(null)
+ channel = null
+ events = null
+ fixStream = null
+ context = null
+ }
+
+ override fun onAttachedToActivity(activityBinding: ActivityPluginBinding) {
+ binding = activityBinding
+ activityBinding.addRequestPermissionsResultListener(this)
+ }
+
+ override fun onDetachedFromActivityForConfigChanges() = detach()
+
+ override fun onReattachedToActivityForConfigChanges(
+ activityBinding: ActivityPluginBinding,
+ ) = onAttachedToActivity(activityBinding)
+
+ override fun onDetachedFromActivity() {
+ detach()
+ pendingPermission?.error("no_activity", "activity went away", null)
+ pendingPermission = null
+ }
+
+ private fun detach() {
+ binding?.removeRequestPermissionsResultListener(this)
+ binding = null
+ }
+
+ 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)
+ "requestPermission" ->
+ request(ctx, call.argument("precise") ?: true, result)
+ "currentLocation" -> current(ctx, result)
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun request(ctx: Context, precise: Boolean, result: MethodChannel.Result) {
+ if (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
+ val perms = if (precise) {
+ arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, COARSE)
+ } else {
+ arrayOf(COARSE)
+ }
+ ActivityCompat.requestPermissions(activity, perms, REQUEST_CODE)
+ }
+
+ override fun onRequestPermissionsResult(
+ requestCode: Int,
+ permissions: Array,
+ grantResults: IntArray,
+ ): Boolean {
+ if (requestCode != REQUEST_CODE) return false
+ val result = pendingPermission ?: return true
+ pendingPermission = null
+ val granted = grantResults.any { it == PackageManager.PERMISSION_GRANTED }
+ result.success(
+ when {
+ granted -> GRANTED
+ // No rationale after a refusal means "don't ask again" (or a
+ // policy block): the prompt will not show any more.
+ binding?.activity?.let { permanentlyDenied(it) } == true ->
+ DENIED_FOREVER
+ else -> DENIED
+ },
+ )
+ return true
+ }
+
+ private fun permanentlyDenied(activity: Activity): Boolean =
+ !ActivityCompat.shouldShowRequestPermissionRationale(activity, COARSE)
+
+ 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)
+ var answered = false
+ val reply = { location: Location? ->
+ if (!answered) {
+ answered = true
+ val fix = location ?: lastKnown(lm, ctx)
+ if (fix == null) {
+ result.error("no_fix", "no location from $provider", null)
+ } else {
+ result.success(toMap(fix))
+ }
+ }
+ }
+ try {
+ LocationManagerCompat.getCurrentLocation(
+ lm,
+ provider,
+ CancellationSignal(),
+ ContextCompat.getMainExecutor(ctx),
+ ) { reply(it) }
+ } catch (e: SecurityException) {
+ result.error("denied", e.message, 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
+ return try {
+ lm.getProviders(true)
+ .mapNotNull { lm.getLastKnownLocation(it) }
+ .maxByOrNull { it.time }
+ } catch (_: SecurityException) {
+ null
+ }
+ }
+
+ companion object {
+ const val CHANNEL = "dev.kuhy/platform_location"
+ private const val REQUEST_CODE = 0x10c4
+ private const val COARSE = Manifest.permission.ACCESS_COARSE_LOCATION
+ 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),
+ )
+ }
+}
diff --git a/platform_location/lib/platform_location.dart b/platform_location/lib/platform_location.dart
new file mode 100644
index 0000000..01b24df
--- /dev/null
+++ b/platform_location/lib/platform_location.dart
@@ -0,0 +1,150 @@
+/// Android location through the platform `LocationManager`, owned once for
+/// every app.
+///
+/// Why a plugin and not geolocator: geolocator_android links
+/// `com.google.android.gms:play-services-location` (and with it
+/// play-services-base, -basement and -tasks, all non-free) even with
+/// `forceLocationManager: true`. This package talks to AOSP's
+/// `LocationManager` through androidx `LocationManagerCompat` only.
+///
+/// Being a real plugin (not a MainActivity channel), it also registers in
+/// background engines such as a flutter_foreground_task service isolate.
+/// Everything but [PlatformLocation.requestPermission] works there.
+///
+/// Tests swap [PlatformLocation.instance] for a fake, the way geolocator's
+/// `GeolocatorPlatform.instance` used to be swapped.
+library;
+
+import 'package:flutter/services.dart';
+
+/// The method channel `PlatformLocationPlugin.kt` answers on.
+const kPlatformLocationChannel = MethodChannel('dev.kuhy/platform_location');
+
+/// The event channel that streams fixes.
+const kPlatformLocationFixes = EventChannel('dev.kuhy/platform_location/fixes');
+
+/// Whether the app may read the location.
+enum LocationPermissionState {
+ /// Fine or coarse location is granted.
+ granted,
+
+ /// Not granted; asking again may show the system prompt.
+ denied,
+
+ /// Refused for good; only the system settings can change it.
+ deniedForever;
+
+ static LocationPermissionState _parse(String? name) =>
+ LocationPermissionState.values.firstWhere(
+ (s) => s.name == name,
+ orElse: () => LocationPermissionState.denied,
+ );
+}
+
+/// One location fix.
+class LocationFix {
+ /// Creates a fix.
+ const LocationFix({
+ required this.time,
+ required this.latitude,
+ required this.longitude,
+ this.altitude = 0,
+ this.accuracy = 0,
+ this.isMock = false,
+ });
+
+ /// Decodes the map the Kotlin side sends.
+ factory LocationFix.fromMap(Map