mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-21 00:12:31 +01:00
platform_location: LocationManager plugin, no gms
Flutter plugin over AOSP LocationManager (androidx LocationManagerCompat): permission check/request, location switch, one-shot fix and a fix stream. Replaces geolocator in umbrella and workout_app, whose Android side links non-free play-services-location even with forceLocationManager. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c394641272
commit
44ed951630
36
.github/workflows/platform-location-tests.yml
vendored
Normal file
36
.github/workflows/platform-location-tests.yml
vendored
Normal file
@ -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
|
||||
17
README.md
17
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
|
||||
|
||||
7
platform_location/.gitignore
vendored
Normal file
7
platform_location/.gitignore
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
.dart_tool/
|
||||
.packages
|
||||
build/
|
||||
pubspec.lock
|
||||
coverage/
|
||||
*.iml
|
||||
pubspec_overrides.yaml
|
||||
61
platform_location/.pre-commit-config.yaml
Normal file
61
platform_location/.pre-commit-config.yaml
Normal file
@ -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]
|
||||
51
platform_location/README.md
Normal file
51
platform_location/README.md
Normal file
@ -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.
|
||||
38
platform_location/analysis_options.yaml
Normal file
38
platform_location/analysis_options.yaml
Normal file
@ -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
|
||||
59
platform_location/android/build.gradle.kts
Normal file
59
platform_location/android/build.gradle.kts
Normal file
@ -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")
|
||||
}
|
||||
1
platform_location/android/settings.gradle.kts
Normal file
1
platform_location/android/settings.gradle.kts
Normal file
@ -0,0 +1 @@
|
||||
rootProject.name = "platform_location"
|
||||
1
platform_location/android/src/main/AndroidManifest.xml
Normal file
1
platform_location/android/src/main/AndroidManifest.xml
Normal file
@ -0,0 +1 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
|
||||
@ -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
|
||||
}
|
||||
}
|
||||
@ -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<Boolean>("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<out String>,
|
||||
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<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),
|
||||
)
|
||||
}
|
||||
}
|
||||
150
platform_location/lib/platform_location.dart
Normal file
150
platform_location/lib/platform_location.dart
Normal file
@ -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<Object?, Object?> map) => LocationFix(
|
||||
time: DateTime.fromMillisecondsSinceEpoch(
|
||||
(map['time']! as num).toInt(),
|
||||
isUtc: true,
|
||||
),
|
||||
latitude: (map['latitude']! as num).toDouble(),
|
||||
longitude: (map['longitude']! as num).toDouble(),
|
||||
altitude: (map['altitude'] as num?)?.toDouble() ?? 0,
|
||||
accuracy: (map['accuracy'] as num?)?.toDouble() ?? 0,
|
||||
isMock: map['isMock'] as bool? ?? false,
|
||||
);
|
||||
|
||||
/// When the fix was taken (UTC).
|
||||
final DateTime time;
|
||||
|
||||
/// Degrees north.
|
||||
final double latitude;
|
||||
|
||||
/// Degrees east.
|
||||
final double longitude;
|
||||
|
||||
/// Metres above the WGS84 ellipsoid; 0 when the provider has none.
|
||||
final double altitude;
|
||||
|
||||
/// Horizontal accuracy radius in metres; 0 when unknown.
|
||||
final double accuracy;
|
||||
|
||||
/// Whether a mock-location app produced this fix.
|
||||
final bool isMock;
|
||||
}
|
||||
|
||||
/// The location API; [instance] is the seam tests replace.
|
||||
abstract class PlatformLocation {
|
||||
/// The active implementation; a test assigns a fake here.
|
||||
static PlatformLocation instance = MethodChannelPlatformLocation();
|
||||
|
||||
/// Whether the device's location switch is on.
|
||||
Future<bool> isLocationEnabled();
|
||||
|
||||
/// The permission as it stands; never prompts. Reports
|
||||
/// [LocationPermissionState.denied], never `deniedForever`: Android only
|
||||
/// tells a permanent refusal apart right after a request.
|
||||
Future<LocationPermissionState> checkPermission();
|
||||
|
||||
/// Shows the system prompt (needs a foreground Activity). [precise] asks
|
||||
/// for fine location as well as coarse.
|
||||
Future<LocationPermissionState> requestPermission({bool precise = true});
|
||||
|
||||
/// One fresh fix; throws a [PlatformException] when there is none
|
||||
/// (no permission, location off, timeout).
|
||||
Future<LocationFix> currentLocation();
|
||||
|
||||
/// Fixes about every [interval], best accuracy, until cancelled.
|
||||
Stream<LocationFix> fixes({Duration interval = const Duration(seconds: 2)});
|
||||
}
|
||||
|
||||
/// [PlatformLocation] over [kPlatformLocationChannel].
|
||||
class MethodChannelPlatformLocation extends PlatformLocation {
|
||||
@override
|
||||
Future<bool> isLocationEnabled() async =>
|
||||
await kPlatformLocationChannel.invokeMethod<bool>('isLocationEnabled') ??
|
||||
false;
|
||||
|
||||
@override
|
||||
Future<LocationPermissionState> checkPermission() async =>
|
||||
LocationPermissionState._parse(
|
||||
await kPlatformLocationChannel.invokeMethod<String>('checkPermission'),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<LocationPermissionState> requestPermission({
|
||||
bool precise = true,
|
||||
}) async => LocationPermissionState._parse(
|
||||
await kPlatformLocationChannel.invokeMethod<String>('requestPermission', {
|
||||
'precise': precise,
|
||||
}),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<LocationFix> currentLocation() async {
|
||||
final map = await kPlatformLocationChannel
|
||||
.invokeMapMethod<Object?, Object?>('currentLocation');
|
||||
if (map == null) {
|
||||
throw PlatformException(code: 'no_fix', message: 'no location');
|
||||
}
|
||||
return LocationFix.fromMap(map);
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<LocationFix> fixes({Duration interval = const Duration(seconds: 2)}) =>
|
||||
kPlatformLocationFixes
|
||||
.receiveBroadcastStream({'intervalMs': interval.inMilliseconds})
|
||||
.map((e) => LocationFix.fromMap(e as Map<Object?, Object?>));
|
||||
}
|
||||
26
platform_location/pubspec.yaml
Normal file
26
platform_location/pubspec.yaml
Normal file
@ -0,0 +1,26 @@
|
||||
name: platform_location
|
||||
description: >-
|
||||
Android location through the platform LocationManager (AOSP,
|
||||
LocationManagerCompat): permission, location switch, one-shot fix and a
|
||||
fix stream. No Google Play services in the APK, unlike geolocator.
|
||||
publish_to: 'none'
|
||||
version: 0.1.0
|
||||
|
||||
environment:
|
||||
sdk: ^3.12.2
|
||||
|
||||
dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
very_good_analysis: ^11.0.0
|
||||
|
||||
flutter:
|
||||
plugin:
|
||||
platforms:
|
||||
android:
|
||||
package: dev.kuhy.platform_location
|
||||
pluginClass: PlatformLocationPlugin
|
||||
32
platform_location/scripts/check_coverage.sh
Executable file
32
platform_location/scripts/check_coverage.sh
Executable file
@ -0,0 +1,32 @@
|
||||
#!/bin/bash
|
||||
|
||||
# ============================================================================
|
||||
# Fail if lcov line coverage drops below a threshold.
|
||||
#
|
||||
# Thin delegate to the shared gate in ~/src/utils/scripts, which owns the parsing
|
||||
# and the threshold comparison. This file used to be a byte-identical copy of
|
||||
# that logic; three such copies existed, which is how one package's idea of
|
||||
# "covered" drifts from every other package's.
|
||||
#
|
||||
# Usage: check_coverage.sh <lcov.info> <min_percent>
|
||||
# ============================================================================
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# Repo-relative, resolved from this script's own location: an absolute
|
||||
# /home/... path exits 127 on an Actions runner.
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
readonly SCRIPT_DIR
|
||||
readonly SHARED_GATE="${SCRIPT_DIR}/../../scripts/check_coverage.sh"
|
||||
|
||||
main() {
|
||||
if [[ ! -f "$SHARED_GATE" ]]; then
|
||||
echo "Error: shared coverage gate not found at $SHARED_GATE" >&2
|
||||
echo " It lives in the utils repo at scripts/check_coverage.sh." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
exec bash "$SHARED_GATE" "$@"
|
||||
}
|
||||
|
||||
main "$@"
|
||||
119
platform_location/test/platform_location_test.dart
Normal file
119
platform_location/test/platform_location_test.dart
Normal file
@ -0,0 +1,119 @@
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:platform_location/platform_location.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
final calls = <MethodCall>[];
|
||||
Object? Function(MethodCall) answer = (_) => null;
|
||||
|
||||
setUp(() {
|
||||
calls.clear();
|
||||
messenger.setMockMethodCallHandler(kPlatformLocationChannel, (c) async {
|
||||
calls.add(c);
|
||||
return answer(c);
|
||||
});
|
||||
});
|
||||
tearDown(() {
|
||||
messenger
|
||||
..setMockMethodCallHandler(kPlatformLocationChannel, null)
|
||||
..setMockStreamHandler(kPlatformLocationFixes, null);
|
||||
});
|
||||
|
||||
final fixMap = <Object?, Object?>{
|
||||
'time': 1762689600000,
|
||||
'latitude': 52.2297,
|
||||
'longitude': 21.0122,
|
||||
'altitude': 110.5,
|
||||
'accuracy': 4,
|
||||
'isMock': true,
|
||||
};
|
||||
|
||||
test('the default instance talks over the method channel', () {
|
||||
expect(PlatformLocation.instance, isA<MethodChannelPlatformLocation>());
|
||||
});
|
||||
|
||||
test('isLocationEnabled reads the switch, null means off', () async {
|
||||
final api = MethodChannelPlatformLocation();
|
||||
answer = (_) => true;
|
||||
expect(await api.isLocationEnabled(), isTrue);
|
||||
answer = (_) => null;
|
||||
expect(await api.isLocationEnabled(), isFalse);
|
||||
expect(calls.first.method, 'isLocationEnabled');
|
||||
});
|
||||
|
||||
test('permission names map to states, unknown means denied', () async {
|
||||
final api = MethodChannelPlatformLocation();
|
||||
for (final state in LocationPermissionState.values) {
|
||||
answer = (_) => state.name;
|
||||
expect(await api.checkPermission(), state);
|
||||
}
|
||||
answer = (_) => 'whatever';
|
||||
expect(await api.checkPermission(), LocationPermissionState.denied);
|
||||
answer = (_) => null;
|
||||
expect(await api.checkPermission(), LocationPermissionState.denied);
|
||||
});
|
||||
|
||||
test('requestPermission passes precise', () async {
|
||||
final api = MethodChannelPlatformLocation();
|
||||
answer = (_) => 'deniedForever';
|
||||
expect(
|
||||
await api.requestPermission(precise: false),
|
||||
LocationPermissionState.deniedForever,
|
||||
);
|
||||
answer = (_) => 'granted';
|
||||
expect(await api.requestPermission(), LocationPermissionState.granted);
|
||||
expect(calls.map((c) => c.arguments), [
|
||||
{'precise': false},
|
||||
{'precise': true},
|
||||
]);
|
||||
});
|
||||
|
||||
test('currentLocation decodes a fix in UTC', () async {
|
||||
answer = (_) => fixMap;
|
||||
final fix = await MethodChannelPlatformLocation().currentLocation();
|
||||
expect(fix.time, DateTime.utc(2025, 11, 9, 12));
|
||||
expect(fix.time.isUtc, isTrue);
|
||||
expect((fix.latitude, fix.longitude), (52.2297, 21.0122));
|
||||
expect((fix.altitude, fix.accuracy, fix.isMock), (110.5, 4.0, true));
|
||||
});
|
||||
|
||||
test('missing optional fields default to 0 / not mocked', () {
|
||||
final fix = LocationFix.fromMap({'time': 0, 'latitude': 1, 'longitude': 2});
|
||||
expect((fix.altitude, fix.accuracy, fix.isMock), (0.0, 0.0, false));
|
||||
});
|
||||
|
||||
test('currentLocation throws when there is no fix', () async {
|
||||
final api = MethodChannelPlatformLocation();
|
||||
answer = (_) => null;
|
||||
await expectLater(
|
||||
api.currentLocation(),
|
||||
throwsA(isA<PlatformException>().having((e) => e.code, 'code', 'no_fix')),
|
||||
);
|
||||
answer = (_) => throw PlatformException(code: 'unavailable');
|
||||
await expectLater(api.currentLocation(), throwsA(isA<PlatformException>()));
|
||||
});
|
||||
|
||||
test('fixes streams decoded fixes with the interval', () async {
|
||||
Object? listenArgs;
|
||||
messenger.setMockStreamHandler(
|
||||
kPlatformLocationFixes,
|
||||
MockStreamHandler.inline(
|
||||
onListen: (args, sink) {
|
||||
listenArgs = args;
|
||||
sink
|
||||
..success(fixMap)
|
||||
..success({...fixMap, 'isMock': false})
|
||||
..endOfStream();
|
||||
},
|
||||
),
|
||||
);
|
||||
final fixes = await MethodChannelPlatformLocation()
|
||||
.fixes(interval: const Duration(seconds: 3))
|
||||
.toList();
|
||||
expect(listenArgs, {'intervalMs': 3000});
|
||||
expect(fixes.map((f) => f.isMock), [true, false]);
|
||||
});
|
||||
}
|
||||
@ -104,6 +104,7 @@ verify() {
|
||||
check_tag godot-dev-tools godot_dev_tools
|
||||
check_tag app-errors app_errors
|
||||
check_tag kuhy-credit kuhy_credit
|
||||
check_tag platform_location platform_location
|
||||
check_sickdays
|
||||
check_app_errors
|
||||
if [[ "$FAILED" -ne 0 ]]; then
|
||||
|
||||
Loading…
Reference in New Issue
Block a user