WIP: Add new location service, disable old.

Note: this commit does not compile
This commit is contained in:
Olof Hedman
2025-09-24 10:02:50 +02:00
parent 7e9973c773
commit 0d1e54fcd8
13 changed files with 372 additions and 531 deletions

View File

@@ -1,25 +1,25 @@
package app.klottr.location
import android.content.Context
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.Priority
import kotlinx.coroutines.tasks.await
/** Android-implementation som använder FusedLocationProvider. */
object AndroidLocationProvider : LocationProvider {
/** Hämtar lastLocation och faller tillbaka till getCurrentLocation. */
suspend fun currentOrLastKnown(context: Context): GeoPoint? {
val client = LocationServices.getFusedLocationProviderClient(context)
return try {
val last = client.lastLocation.await()
val loc = last ?: client.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
loc?.let { GeoPoint(it.latitude, it.longitude) }
} catch (_: Exception) {
null
}
}
// Interface-override finns för framtida DI utan Context (används ej av :app idag).
override suspend fun currentOrLastKnown(): GeoPoint? = null
}
//import android.content.Context
//import com.google.android.gms.location.LocationServices
//import com.google.android.gms.location.Priority
//import kotlinx.coroutines.tasks.await
//
///** Android-implementation som använder FusedLocationProvider. */
//object AndroidLocationProvider : LocationProvider {
//
// /** Hämtar lastLocation och faller tillbaka till getCurrentLocation. */
// suspend fun currentOrLastKnown(context: Context): GeoPoint? {
// val client = LocationServices.getFusedLocationProviderClient(context)
// return try {
// val last = client.lastLocation.await()
// val loc = last ?: client.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
// loc?.let { GeoPoint(it.latitude, it.longitude) }
// } catch (_: Exception) {
// null
// }
// }
//
// // Interface-override finns för framtida DI utan Context (används ej av :app idag).
// override suspend fun currentOrLastKnown(): GeoPoint? = null
//}

View File

@@ -1,7 +1,7 @@
package app.klottr.location
/** Android-implementationen håller bara ett volatilt fält. */
actual object LastLocationStore {
@Volatile
actual var lastKnown: GeoPoint? = null
}
///** Android-implementationen håller bara ett volatilt fält. */
//actual object LastLocationStore {
// @Volatile
// actual var lastKnown: GeoPoint? = null
//}

View File

@@ -0,0 +1,122 @@
package app.klottr.location
import android.annotation.SuppressLint
import android.content.Context
import android.location.LocationManager
import android.os.Looper
import androidx.core.content.ContextCompat
import android.content.pm.PackageManager
import com.google.android.gms.location.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.tasks.await
private class AndroidLocationService(
private val appContext: Context,
private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
) : LocationService {
private val fused by lazy { LocationServices.getFusedLocationProviderClient(appContext) }
private var callback: LocationCallback? = null
private val _location = MutableStateFlow<GeoPoint?>(null)
override val location: StateFlow<GeoPoint?> = _location
private fun hasPermission(): Boolean {
val fine = ContextCompat.checkSelfPermission(
appContext, android.Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
val coarse = ContextCompat.checkSelfPermission(
appContext, android.Manifest.permission.ACCESS_COARSE_LOCATION
) == PackageManager.PERMISSION_GRANTED
return fine || coarse
}
override fun start(updates: LocationUpdates) {
if (callback != null) return
if (!hasPermission()) return
val req = LocationRequest.Builder(
if (updates.highAccuracy) Priority.PRIORITY_HIGH_ACCURACY else Priority.PRIORITY_BALANCED_POWER_ACCURACY,
updates.desiredIntervalMillis
)
.setMinUpdateIntervalMillis(updates.fastestIntervalMillis)
.build()
callback = object : LocationCallback() {
override fun onLocationResult(result: LocationResult) {
val l = result.lastLocation ?: return
val p = GeoPoint(
lat = l.latitude,
lon = l.longitude,
accuracyMeters = l.accuracy.toDouble(),
timeMillis = l.time
)
_location.value = p
LastLocationStore.update(p)
}
}
//noinspection MissingPermission
fused.requestLocationUpdates(req, callback!!, Looper.getMainLooper())
scope.launch { _location.value ?: run { _location.value = lastKnownImmediate() } }
}
override fun stop() {
callback?.let { fused.removeLocationUpdates(it) }
callback = null
}
@SuppressLint("MissingPermission")
private suspend fun lastKnownImmediate(): GeoPoint? {
if (!hasPermission()) return null
return try {
val l = fused.lastLocation.await() ?: return null
GeoPoint(l.latitude, l.longitude, l.accuracy.toDouble(), l.time).also { LastLocationStore.update(it) }
} catch (_: Throwable) { null }
}
@SuppressLint("MissingPermission")
override suspend fun current(highAccuracy: Boolean, timeoutMillis: Long): GeoPoint? {
if (!hasPermission()) return _location.value ?: LastLocationStore.lastKnown.value
// Try current quick, with fallback to last known
return try {
withTimeout(timeoutMillis) {
val loc = fused.getCurrentLocation(
if (highAccuracy) Priority.PRIORITY_HIGH_ACCURACY else Priority.PRIORITY_BALANCED_POWER_ACCURACY,
null
).await()
loc?.let {
GeoPoint(it.latitude, it.longitude, it.accuracy.toDouble(), it.time).also { p ->
_location.value = p
LastLocationStore.update(p)
}
} ?: lastKnownImmediate()
}
} catch (_: Throwable) {
_location.value ?: LastLocationStore.lastKnown.value ?: lastKnownImmediate()
}
}
override suspend fun isLocationEnabled(): Boolean {
val lm = appContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
return lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
}
}
@Suppress("FunctionName")
internal fun AndroidLocationService(appContext: Context): LocationService =
AndroidLocationService(appContext)
actual object LocationServiceProvider {
private var instance: LocationService? = null
fun init(appContext: Context) { // optional: call once from Application.onCreate()
if (instance == null) instance = AndroidLocationService(appContext.applicationContext)
}
actual fun get(): LocationService {
return instance ?: error("LocationServiceProvider not initialized. Call LocationServiceProvider.init(context).")
}
}

View File

@@ -1,6 +1,6 @@
package app.klottr.location
/** Delad platsstore: senaste kända position som enkel GeoPoint. */
expect object LastLocationStore {
var lastKnown: GeoPoint?
}
///** Delad platsstore: senaste kända position som enkel GeoPoint. */
//expect object LastLocationStore {
// var lastKnown: GeoPoint?
//}

View File

@@ -1,10 +1,10 @@
package app.klottr.location
/** Enkel delad platsmodell för KMP. */
data class GeoPoint(val lat: Double, val lon: Double)
/** Gränssnitt för plattforms-specifik platsinhämtning. */
interface LocationProvider {
/** Returnerar aktuell plats eller senaste kända, eller null vid fel/tidsutlöpning. */
suspend fun currentOrLastKnown(): GeoPoint?
}
///** Enkel delad platsmodell för KMP. */
//data class GeoPoint(val lat: Double, val lon: Double)
//
///** Gränssnitt för plattforms-specifik platsinhämtning. */
//interface LocationProvider {
// /** Returnerar aktuell plats eller senaste kända, eller null vid fel/tidsutlöpning. */
// suspend fun currentOrLastKnown(): GeoPoint?
//}

View File

@@ -0,0 +1,53 @@
package app.klottr.location
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
/**
* Platform-independent, Flow-based location API.
* Everything used by UI/Workers should depend on this interface.
*/
interface LocationService {
/** Last known or most recent location (null until the first fix). */
val location: StateFlow<GeoPoint?>
/** Start continuous updates (idempotent). */
fun start(updates: LocationUpdates = LocationUpdates())
/** Stop updates (idempotent). */
fun stop()
/** Try to get a fresh fix (falls back to last known). */
suspend fun current(highAccuracy: Boolean = true, timeoutMillis: Long = 10_000): GeoPoint?
/** Whether platform indicates location services are enabled. */
suspend fun isLocationEnabled(): Boolean
}
/** Minimal, platform-agnostic location model for UI/worker. */
data class GeoPoint(
val lat: Double,
val lon: Double,
val accuracyMeters: Double? = null,
val timeMillis: Long? = null,
)
data class LocationUpdates(
val desiredIntervalMillis: Long = 5_000,
val fastestIntervalMillis: Long = 2_000,
val highAccuracy: Boolean = true,
)
/** Simple, common store (replaces various platform stores). */
object LastLocationStore {
private val _lastKnown = MutableStateFlow<GeoPoint?>(null)
val lastKnown: StateFlow<GeoPoint?> = _lastKnown.asStateFlow()
fun update(p: GeoPoint?) { _lastKnown.value = p }
}
/** Accessor to a shared instance (can be replaced via DI if you like). */
expect object LocationServiceProvider {
fun get(): LocationService
}

View File

@@ -1,6 +1,6 @@
package app.klottr.location
/** iOS-stub tills riktig plats läggs till. */
object IosLocationProvider : LocationProvider {
override suspend fun currentOrLastKnown(): GeoPoint? = null
}
//
///** iOS-stub tills riktig plats läggs till. */
//object IosLocationProvider : LocationProvider {
// override suspend fun currentOrLastKnown(): GeoPoint? = null
//}

View File

@@ -1,6 +1,6 @@
package app.klottr.location
/** iOS implementation keeps the last known point in memory. */
actual object LastLocationStore {
actual var lastKnown: GeoPoint? = null
}
///** iOS implementation keeps the last known point in memory. */
//actual object LastLocationStore {
// actual var lastKnown: GeoPoint? = null
//}

View File

@@ -0,0 +1,88 @@
package app.klottr.location
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.useContents
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import platform.CoreLocation.*
import platform.Foundation.NSError
import platform.Foundation.timeIntervalSince1970
import platform.darwin.NSObject
private class IOSLocationService(
private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
) : NSObject(), LocationService, CLLocationManagerDelegateProtocol {
private val manager = CLLocationManager()
private val _location = MutableStateFlow<GeoPoint?>(null)
override val location: StateFlow<GeoPoint?> = _location
private var started = false
private var highAccuracy = true
init {
manager.delegate = this
}
override fun start(updates: LocationUpdates) {
if (started) return
started = true
highAccuracy = updates.highAccuracy
manager.desiredAccuracy = if (updates.highAccuracy) kCLLocationAccuracyBest else kCLLocationAccuracyHundredMeters
manager.distanceFilter = kCLDistanceFilterNone
when (CLLocationManager.authorizationStatus()) {
kCLAuthorizationStatusNotDetermined -> manager.requestWhenInUseAuthorization()
else -> {}
}
manager.startUpdatingLocation()
}
override fun stop() {
if (!started) return
manager.stopUpdatingLocation()
started = false
}
override suspend fun current(highAccuracy: Boolean, timeoutMillis: Long): GeoPoint? {
// On iOS, startUpdatingLocation yields callbacks; just return latest within timeout.
if (!started) start(LocationUpdates(highAccuracy = highAccuracy))
return try {
withTimeout(timeoutMillis) {
while (_location.value == null) delay(50)
_location.value
}
} catch (_: Throwable) {
_location.value ?: LastLocationStore.lastKnown.value
}
}
override suspend fun isLocationEnabled(): Boolean {
return CLLocationManager.locationServicesEnabled()
}
// CLLocationManagerDelegate
@OptIn(ExperimentalForeignApi::class)
override fun locationManager(manager: CLLocationManager, didUpdateLocations: List<*>) {
val last = (didUpdateLocations.lastOrNull() as? CLLocation) ?: return
val ts = last.timestamp.timeIntervalSince1970() * 1000.0
last.coordinate.useContents {
val lat = latitude
val lon = longitude
val p = GeoPoint(
lat = lat,
lon = lon,
accuracyMeters = last.horizontalAccuracy,
timeMillis = ts.toLong()
)
_location.value = p
LastLocationStore.update(p)
}
}
override fun locationManager(manager: CLLocationManager, didFailWithError: NSError) { /* ignore */ }
}
actual object LocationServiceProvider {
private val instance: LocationService by lazy { IOSLocationService() }
actual fun get(): LocationService = instance
}