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,348 +0,0 @@
package app.klottr
import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import app.klottr.net.Geocache
import app.klottr.net.NoteDTO
import app.klottr.util.FoundStore
import app.klottr.util.LastLocationStore
import app.klottr.util.SettingsStore
// import app.klottr.util.distanceMeters
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.Priority
import com.google.android.gms.maps.model.LatLng
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
import kotlin.math.roundToInt
class LocationService : Service() {
companion object {
private const val CHANNEL_LOCATION_ID = "Klottr_location" // för foreground, tyst
private const val CHANNEL_HITS_ID = "Klottr_hits" // NY kanal för fynd-notiser
const val ACTION_FOUND_UPDATED = "app.klottr.ACTION_FOUND_UPDATED"
const val ACTION_CLEAR_FOUND_SESSION = "app.klottr.ACTION_CLEAR_FOUND_SESSION"
const val ACTION_RESCAN_NOW = "app.klottr.ACTION_RESCAN_NOW"
const val ACTION_LOCATION_TICK = "app.klottr.ACTION_LOCATION_TICK"
const val ACTION_SUPPRESS_NOTIFY = "app.klottr.ACTION_SUPPRESS_NOTIFY" // Tysta notiser för ett id
}
private val scope = CoroutineScope(Dispatchers.IO + Job())
private val fused by lazy { LocationServices.getFusedLocationProviderClient(this) }
// Sessiontillstånd – används för “gå utanför ~200 m → tillåt om-avisering”
private val notifiedWhileInside = mutableMapOf<String, Boolean>() // key(layer:id) -> om vi redan aviserat denna session.
private val lastKnownDistance = mutableMapOf<String, Int>() // senaste uppmätta avståndet (meter).
private val suppressedUntil = mutableMapOf<String, Long>() // key(layer:id) -> tyst till tidsstämpel
private lateinit var callback: LocationCallback
override fun onBind(intent: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
ensureChannel()
startForeground(1, persistentNotification())
startLocation()
}
override fun onDestroy() {
try { fused.removeLocationUpdates(callback) } catch (_: Exception) {}
super.onDestroy()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
ACTION_CLEAR_FOUND_SESSION -> {
notifiedWhileInside.clear()
lastKnownDistance.clear()
}
ACTION_SUPPRESS_NOTIFY -> {
val layer = intent.getStringExtra("layer")
val id = intent.getStringExtra("id")
val ttl = intent.getLongExtra("ttlMs", 60_000L) // default 60s
if (layer != null && id != null) {
suppressedUntil[key(layer, id)] = System.currentTimeMillis() + ttl // Lägg in tystnad
}
}
ACTION_RESCAN_NOW -> {
scope.launch {
val loc = try {
fused.lastLocation.await()
?: fused.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
} catch (_: Exception) { null }
val L = loc ?: LastLocationStore.lastKnownLocation
if (L != null) {
// Håll last known i sync om vi faktiskt fick en färsk position
LastLocationStore.lastKnownLocation = L
// Uppdatera away-flaggor för den position du ska scanna mot
FoundStore.updateAwayFlags(L.latitude, L.longitude)
// 1) Tala om att data (ev. away) kan ha ändrats
sendBroadcast(Intent(ACTION_FOUND_UPDATED))
// 2) Tvinga omritning av “Hittat” så avstånd/fetstil uppdateras direkt
sendBroadcast(Intent(ACTION_LOCATION_TICK))
// 3) Kör matchningen
checkMatches(L.latitude, L.longitude)
// Skicka ett tick så hittat uppdaterar avstånd/fet stil.
sendBroadcast(Intent(ACTION_LOCATION_TICK))
}
}
}
}
return START_STICKY
}
// ---- Platsuppdateringar ----
private fun startLocation() {
if (!hasLocationPerms()) return
val req = LocationRequest.create().apply {
interval = 4_000L
fastestInterval = 2_000L
smallestDisplacement = 3f
priority = Priority.PRIORITY_HIGH_ACCURACY
maxWaitTime = 5_000L
}
callback = object : LocationCallback() {
override fun onLocationResult(result: LocationResult) {
val loc = result.lastLocation ?: return
LastLocationStore.lastKnownLocation = loc
sendBroadcast(Intent(ACTION_LOCATION_TICK))
scope.launch {
// Uppdatera away-flaggor för ALLA sparade fynd utifrån aktuell position
FoundStore.updateAwayFlags(loc.latitude, loc.longitude)
// (UI lyssnar på SharedPreferences, men vi pingar ändå för säkerhets skull)
sendBroadcast(Intent(ACTION_FOUND_UPDATED))
// Matcha på senaste
checkMatches(loc.latitude, loc.longitude)
// Försök förfina om noggrannheten är sämre än ~30 m
val acc = loc.accuracy
if (acc.isFinite() && acc > 30f) {
try {
val refined = fused.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
if (refined != null) {
LastLocationStore.lastKnownLocation = refined
sendBroadcast(Intent(ACTION_LOCATION_TICK))
FoundStore.updateAwayFlags(refined.latitude, refined.longitude)
sendBroadcast(Intent(ACTION_FOUND_UPDATED))
checkMatches(refined.latitude, refined.longitude)
}
} catch (_: Exception) {
// ignore
}
}
}
}
}
try {
fused.requestLocationUpdates(req, callback, mainLooper)
} catch (_: SecurityException) {
// saknar tillstånd
}
}
private fun hasLocationPerms(): Boolean {
val fine = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
val coarse = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
return fine || coarse
}
// ---- Matchning ----
private suspend fun checkMatches(lat: Double, lon: Double) {
// Just nu kör vi bara klotter här (20 m). Wikipedia/DigitaltMuseum/Fornsök scannas i UI vid behov.
val showKlotter = SettingsStore.getShowKlotter()
if (showKlotter) {
val nearby: List<NoteDTO> = try {
Geocache.getNearby(lat, lon, radiusMeters = 120, ttlMs = 0L)
} catch (_: Exception) {
emptyList()
}
for (n in nearby) {
// Använder FQN för att säkert länka den delade distanceMeters från :shared.
val d = app.klottr.util.distanceMeters(lat, lon, n.a, n.o).roundToInt()
handleCandidate(
layer = FoundStore.LAYER_KLOTTER,
id = n.i.toString(),
label = n.t.orEmpty(),
pt = LatLng(n.a, n.o),
distanceM = d,
insideRadiusM = 20,
onlyNew = SettingsStore.getOnlyNewHits()
)
}
}
}
private fun key(layer: String, id: String) = "$layer:$id"
private suspend fun handleCandidate(
layer: String,
id: String,
label: String,
pt: LatLng,
distanceM: Int,
insideRadiusM: Int,
onlyNew: Boolean
) {
val k = key(layer, id)
// Session-baserad återinträdesdetektion (för att slå av påminnelse tills man gått utanför ~200 m)
val OUTSIDE_RESET_M = 200
val lastD = lastKnownDistance[k]
lastKnownDistance[k] = distanceM
val reenteredSession = (lastD != null && lastD > OUTSIDE_RESET_M && distanceM <= insideRadiusM)
if (reenteredSession) {
// tillåt ny notis denna session
notifiedWhileInside[k] = false
}
// Lagrings-baserad re-arm: om FoundStore flaggat "away=true" och vi nu är inne i radien
val wasAwayStore = FoundStore.isAway(layer, id)
if (distanceM <= insideRadiusM) {
val wasNotifiedThisSession = notifiedWhileInside[k] == true
val alreadyFound = FoundStore.isFound(layer, id)
val now = System.currentTimeMillis()
// Markera i FoundStore:
// - alltid vid första fyndet
// - även vid återinträde (wasAwayStore), oavsett onlyNew, så last_visit uppdateras
// - (behåller session-reentry för bakåtkompabilitet)
val shouldMark = !alreadyFound || wasAwayStore || (!onlyNew && reenteredSession)
if (shouldMark) {
val marked = FoundStore.markFound(layer, id, label, pt.latitude, pt.longitude, now)
if (marked) sendBroadcast(Intent(ACTION_FOUND_UPDATED))
}
// Notiser:
// - onlyNew=true → bara för helt nya (inte för återinträde)
// - onlyNew=false → en gång per session ELLER om re-arm via FoundStore (wasAwayStore) eller session-reentry
val nowMs = System.currentTimeMillis() // Nu
val suppressed = (suppressedUntil[k] ?: 0L) > nowMs // Är tystnad aktiv?
val shouldNotify = if (onlyNew) {
!alreadyFound && !wasNotifiedThisSession && !suppressed
} else {
(!wasNotifiedThisSession || wasAwayStore || reenteredSession) && !suppressed
}
if (suppressed) {
notifiedWhileInside[k] = true // Blockera fler notiser denna session
}
if (shouldNotify) {
val (title, text) = notificationTitleAndText(layer, label, distanceM)
postNotification(k, title, text)
}
// markera att vi nu befinner oss "inne"
notifiedWhileInside[k] = true
} else {
if (distanceM > OUTSIDE_RESET_M) {
// lämnat området tillräckligt långt → tillåt ny notis när vi kommer in igen
notifiedWhileInside[k] = false
}
}
}
private fun notificationTitleAndText(layer: String, label: String, distanceM: Int): Pair<String, String> {
val dist = "≈ ${distanceM} m"
val shown = label.ifBlank {
when (layer) {
FoundStore.LAYER_KLOTTER -> "Okänt klotter"
FoundStore.LAYER_WIKI -> "Wikipedia"
FoundStore.LAYER_DM -> "DigitaltMuseum"
else -> "Plats"
}
}
val title = when (layer) {
FoundStore.LAYER_KLOTTER -> "Funnet klotter"
FoundStore.LAYER_WIKI -> "Funnen Wikipediaplats"
FoundStore.LAYER_DM -> "Funnen DigitaltMuseum-plats"
else -> "Funnen plats"
}
return title to "$shown • $dist"
}
private fun postNotification(tag: String, title: String, text: String) {
val builder = NotificationCompat.Builder(this, CHANNEL_HITS_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(text)
.setPriority(NotificationCompat.PRIORITY_DEFAULT) // har ingen effekt på 8+, men ok
.setAutoCancel(true)
NotificationManagerCompat.from(this).notify(tag, 1001, builder.build())
}
// ---- Foreground-notis & kanal ----
private fun ensureChannel() {
if (Build.VERSION.SDK_INT >= 26) {
val mgr = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
// Foreground-kanal (tyst)
val loc = NotificationChannel(
CHANNEL_LOCATION_ID,
"Klottr plats",
NotificationManager.IMPORTANCE_MIN
).apply { description = "Bakgrundspositionering" }
mgr.createNotificationChannel(loc)
// Fynd-notiser (synliga)
val hits = NotificationChannel(
CHANNEL_HITS_ID,
"Klottr fynd",
NotificationManager.IMPORTANCE_HIGH // vill du ha pling: HIGH
).apply { description = "Aviseringar för nya/återkommande fynd" }
mgr.createNotificationChannel(hits)
}
}
private fun persistentNotification(): Notification {
return NotificationCompat.Builder(this, CHANNEL_LOCATION_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Klottr")
.setContentText("Platsaktivering pågår")
.setOngoing(true)
.build()
}
}

View File

@@ -95,7 +95,6 @@ import app.klottr.create.createNoteFlow
import app.klottr.create.queueNoteDocOutbox import app.klottr.create.queueNoteDocOutbox
import app.klottr.data.AppDatabase import app.klottr.data.AppDatabase
import app.klottr.data.NoteRepository import app.klottr.data.NoteRepository
import app.klottr.location.AndroidLocationProvider
import app.klottr.nearby.FoundOpenAction // Delat åtgärds-ADT import app.klottr.nearby.FoundOpenAction // Delat åtgärds-ADT
import app.klottr.nearby.NearbyBundleShared import app.klottr.nearby.NearbyBundleShared
import app.klottr.nearby.NearbyEntryShared // Delad radmodell import app.klottr.nearby.NearbyEntryShared // Delad radmodell
@@ -151,15 +150,13 @@ import app.klottr.util.NoteDetailCache
import app.klottr.util.OutboxStore import app.klottr.util.OutboxStore
import app.klottr.util.SettingsStore import app.klottr.util.SettingsStore
import app.klottr.util.buildFoundDetailStrings // Delad formatterare (commonMain) import app.klottr.util.buildFoundDetailStrings // Delad formatterare (commonMain)
import androidx.compose.ui.graphics.asImageBitmap import app.klottr.location.LocationServiceProvider
import app.klottr.util.formatCoords import app.klottr.util.formatCoords
import app.klottr.util.formatDistance import app.klottr.util.formatDistance
import app.klottr.work.OutboxWorker import app.klottr.work.OutboxWorker
import coil3.ImageLoader import coil3.ImageLoader
import coil3.compose.setSingletonImageLoaderFactory import coil3.compose.setSingletonImageLoaderFactory
import coil3.toBitmap import coil3.toBitmap
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.location.Priority
// Maps replaced by platform-independent MapContainer // Maps replaced by platform-independent MapContainer
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
@@ -168,7 +165,6 @@ import kotlinx.coroutines.withContext
import java.io.File import java.io.File
import java.util.UUID import java.util.UUID
import kotlin.math.roundToInt import kotlin.math.roundToInt
import com.google.android.gms.location.LocationServices as GmsLocationServices
import app.klottr.maps.CameraPosition as CrossCameraPosition import app.klottr.maps.CameraPosition as CrossCameraPosition
import app.klottr.maps.LatLng as CrossLatLng import app.klottr.maps.LatLng as CrossLatLng
import app.klottr.maps.MapController import app.klottr.maps.MapController
@@ -189,13 +185,14 @@ class MainActivity : ComponentActivity() {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
KLog.setEnabled(BuildConfig.KLLOG_DEBUG) // Styr loggnivå via buildflagga KLog.setEnabled(BuildConfig.KLLOG_DEBUG) // Styr loggnivå via buildflagga
app.klottr.prefs.KvPrefs.init(applicationContext) app.klottr.prefs.KvPrefs.init(applicationContext)
LocationServiceProvider.init(applicationContext)
// FG + (ev) BG platstillstånd // FG + (ev) BG platstillstånd
fgPermissionLauncher = fgPermissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
val fgOk = hasFgLocationPerms(this) val fgOk = hasFgLocationPerms(this)
if (fgOk) { if (fgOk) {
startService(Intent(this, LocationService::class.java)) LocationServiceProvider.get().start()
if (Build.VERSION.SDK_INT >= 29 && !hasBgLocationPerm(this) && pendingBgRequest) { if (Build.VERSION.SDK_INT >= 29 && !hasBgLocationPerm(this) && pendingBgRequest) {
bgPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION) bgPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
} }
@@ -231,7 +228,7 @@ class MainActivity : ComponentActivity() {
// Starta LocationService direkt om vi redan har FG-platstillstånd // Starta LocationService direkt om vi redan har FG-platstillstånd
if (hasFgLocationPerms(this)) { if (hasFgLocationPerms(this)) {
startService(Intent(this, LocationService::class.java)) LocationServiceProvider.get().start()
} }
setContent { setContent {
@@ -301,6 +298,9 @@ private fun KlottrAppShell(
onLogin: () -> Unit, onLogin: () -> Unit,
onLogout: () -> Unit onLogout: () -> Unit
) { ) {
val locService = remember { LocationServiceProvider.get() }
LaunchedEffect(Unit) { locService.start() }
val currentLoc = locService.location.collectAsState(initial = null)
val context = LocalContext.current val context = LocalContext.current
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
@@ -387,17 +387,17 @@ private fun KlottrAppShell(
} }
} }
// Kickstarta avstånd direkt vid appstart // Kickstarta avstånd direkt vid appstart (via KMP LocationService)
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
val gp = AndroidLocationProvider.currentOrLastKnown(context) // Nytt: centraliserad plats val gp = LocationServiceProvider.get().current(highAccuracy = false)
if (gp != null) { if (gp != null) {
// Spara som "senaste kända" och uppdatera away-flaggor LastLocationStore.lastKnownLocation = android.location.Location("kmp").apply {
LastLocationStore.lastKnownLocation = android.location.Location("klottr").apply { latitude = gp.lat
latitude = gp.lat; longitude = gp.lon longitude = gp.lon
} // Nytt: spegla in i din befintliga store time = gp.timeMillis ?: System.currentTimeMillis()
FoundStore.updateAwayFlags(gp.lat, gp.lon) // Oför: men nu med delad modell accuracy = (gp.accuracyMeters ?: 0.0).toFloat()
}
// Tvinga omritning så att avstånd visas utan scroll FoundStore.updateAwayFlags(gp.lat, gp.lon)
locationTick++ locationTick++
} }
} }
@@ -434,22 +434,18 @@ private fun KlottrAppShell(
onDispose { app.klottr.prefs.KvPrefs.removeListener(kvListener) } onDispose { app.klottr.prefs.KvPrefs.removeListener(kvListener) }
} }
// Lyssna på KMP LocationService-flöde istället för broadcast
// Lyssna efter ACTION_LOCATION_TICK LaunchedEffect(currentLoc.value?.lat, currentLoc.value?.lon) {
DisposableEffect(Unit) { currentLoc.value?.let { gp ->
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK) LastLocationStore.lastKnownLocation = android.location.Location("kmp").apply {
val receiver = object : BroadcastReceiver() { latitude = gp.lat
override fun onReceive(ctx: Context?, intent: Intent?) { longitude = gp.lon
locationTick++ // tvinga Compose att rita om där vi läser detta värde time = gp.timeMillis ?: System.currentTimeMillis()
accuracy = (gp.accuracyMeters ?: 0.0).toFloat()
} }
FoundStore.updateAwayFlags(gp.lat, gp.lon)
locationTick++
} }
if (Build.VERSION.SDK_INT >= 33) {
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
} else {
@Suppress("DEPRECATION")
context.registerReceiver(receiver, filter)
}
onDispose { try { context.unregisterReceiver(receiver) } catch (_: Exception) {} }
} }
@@ -468,7 +464,7 @@ private fun KlottrAppShell(
LaunchedEffect(showWiki, wikiRadius, showDm, dmRadius, showFornsok, fornsokRadius) { LaunchedEffect(showWiki, wikiRadius, showDm, dmRadius, showFornsok, fornsokRadius) {
if (!showWiki && !showDm && !showFornsok) return@LaunchedEffect if (!showWiki && !showDm && !showFornsok) return@LaunchedEffect
val gp = AndroidLocationProvider.currentOrLastKnown(context) val gp = LocationServiceProvider.get().current(highAccuracy = false)
if (gp != null) { if (gp != null) {
val anyNew = withContext(Dispatchers.IO) { val anyNew = withContext(Dispatchers.IO) {
scanAndMarkFound( scanAndMarkFound(
@@ -496,7 +492,7 @@ private fun KlottrAppShell(
if (anyNew) { if (anyNew) {
forceEmptyFound = false // Sätt tillbaka visning efter “Glöm alla fynd” forceEmptyFound = false // Sätt tillbaka visning efter “Glöm alla fynd”
refreshFound() // Tvinga omritning av “Senaste” refreshFound() // Tvinga omritning av “Senaste”
context.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED)) // Pinga övriga lyssnare (som tidigare) /* notify listeners inline: refreshFound() already called */
} }
} }
} }
@@ -659,7 +655,7 @@ private fun KlottrAppShell(
showNearby = true showNearby = true
val ctx = context val ctx = context
scope.launch { scope.launch {
val gp = AndroidLocationProvider.currentOrLastKnown(ctx) val gp = LocationServiceProvider.get().current(highAccuracy = false)
if (gp == null) { if (gp == null) {
nearbyLoading = false nearbyLoading = false
nearbyError = "Ingen plats ännu – prova igen." nearbyError = "Ingen plats ännu – prova igen."
@@ -821,10 +817,7 @@ private fun KlottrAppShell(
context.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED)) context.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED))
// 3) Be tjänsten göra en rescan // 3) Be tjänsten göra en rescan
context.startService( // old Android service call removed (handled in shared layer)
Intent(context, LocationService::class.java)
.setAction(LocationService.ACTION_RESCAN_NOW)
)
// 4) Gör även en direkt lokal scan nu (parallellt) → snabb UI-återfyllnad // 4) Gör även en direkt lokal scan nu (parallellt) → snabb UI-återfyllnad
// Använder vår delade scanAndMarkFound så listan fylls utan att vänta på tjänsten. // Använder vår delade scanAndMarkFound så listan fylls utan att vänta på tjänsten.
@@ -837,7 +830,7 @@ private fun KlottrAppShell(
fornsokRadius = fornsokRadius fornsokRadius = fornsokRadius
) )
scope.launch { scope.launch {
val gp = AndroidLocationProvider.currentOrLastKnown(context) val gp = LocationServiceProvider.get().current(highAccuracy = false)
if (gp != null) { if (gp != null) {
val anyNew = withContext(Dispatchers.IO) { val anyNew = withContext(Dispatchers.IO) {
scanAndMarkFound( scanAndMarkFound(
@@ -857,7 +850,7 @@ private fun KlottrAppShell(
if (anyNew) { if (anyNew) {
forceEmptyFound = false // Tillåt visning igen forceEmptyFound = false // Tillåt visning igen
refreshFound() // Rita om “Senaste” refreshFound() // Rita om “Senaste”
context.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED)) // Informera andra lyssnare /* notify listeners inline: refreshFound() already called */
} }
} }
} }
@@ -1622,18 +1615,11 @@ private fun KlotterDialog(
LaunchedEffect(id, lat, lon, label) { LaunchedEffect(id, lat, lon, label) {
loading = !prefilledFromCache loading = !prefilledFromCache
// Hämta ev. färsk plats (fallback LastLocationStore) // Hämta ev. färsk plats
val my = LastLocationStore.lastKnownLocation val my = LocationServiceProvider.get().current(highAccuracy = false)
val fused = GmsLocationServices.getFusedLocationProviderClient(context)
val current = try {
fused.lastLocation.await()
?: fused.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
} catch (_: Exception) {
null
}
val qLat = current?.latitude ?: my?.latitude val qLat = my?.lat
val qLon = current?.longitude ?: my?.longitude val qLon = my?.lon
// --- Delad beslutsregel: ersätter withinRadius/canAttempt/reqLat/reqLon -------------------- // --- Delad beslutsregel: ersätter withinRadius/canAttempt/reqLat/reqLon --------------------
val access = decideDetailAccess( // Ny: Beräkna om vi får hämta + vilka coords som ska skickas val access = decideDetailAccess( // Ny: Beräkna om vi får hämta + vilka coords som ska skickas

View File

@@ -4,7 +4,6 @@ import android.content.Context
import android.content.Intent import android.content.Intent
import androidx.work.CoroutineWorker import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters import androidx.work.WorkerParameters
import app.klottr.LocationService
import app.klottr.net.Geocache import app.klottr.net.Geocache
import app.klottr.net.createNote import app.klottr.net.createNote
import app.klottr.net.createNoteDoc import app.klottr.net.createNoteDoc
@@ -146,7 +145,7 @@ class OutboxWorker(
) )
// Pinga UI så “Senaste” uppdateras direkt // Pinga UI så “Senaste” uppdateras direkt
ctx.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED)) // ctx.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED))
} }
} catch (_: Throwable) { } catch (_: Throwable) {
// Tyst fallback – Workern ska inte krascha pga visuell uppdatering // Tyst fallback – Workern ska inte krascha pga visuell uppdatering

View File

@@ -17,6 +17,7 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue // Gör 'by remember { ... }' läsbart import androidx.compose.runtime.getValue // Gör 'by remember { ... }' läsbart
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
@@ -26,10 +27,10 @@ import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.DialogProperties import androidx.compose.ui.window.DialogProperties
import app.klottr.LocationService
import app.klottr.net.DigitaltMuseumItem import app.klottr.net.DigitaltMuseumItem
import app.klottr.net.FornsokItem import app.klottr.net.FornsokItem
import app.klottr.net.Wikipedia import app.klottr.net.Wikipedia
import app.klottr.location.LocationServiceProvider
import app.klottr.util.SettingsStore import app.klottr.util.SettingsStore
import app.klottr.util.formatCoords import app.klottr.util.formatCoords
import app.klottr.util.formatDistance import app.klottr.util.formatDistance
@@ -54,34 +55,18 @@ fun WikiArticleDialog(
var title by remember { mutableStateOf("") } var title by remember { mutableStateOf("") }
var extract by remember { mutableStateOf("") } var extract by remember { mutableStateOf("") }
// Avståndstext som uppdateras när platsen tickar // Avståndstext uppdateras via KMP LocationService
var wikiDistanceText by remember { mutableStateOf("-") } var wikiDistanceText by remember { mutableStateOf("-") }
val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates() } val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates() }
val locService = remember { LocationServiceProvider.get() }
fun recalcWikiDistance() { LaunchedEffect(Unit) { locService.start() }
val my = app.klottr.util.LastLocationStore.lastKnownLocation val current = locService.location.collectAsState(initial = null)
val d = if (lat != null && lon != null && my != null) LaunchedEffect(current.value?.lat, current.value?.lon, lat, lon) {
app.klottr.util.distanceMeters(my.latitude, my.longitude, lat, lon).roundToInt() val gp = current.value
val d = if (lat != null && lon != null && gp != null)
app.klottr.util.distanceMeters(gp.lat, gp.lon, lat, lon).roundToInt()
else null else null
wikiDistanceText = d?.let { "$it\u00A0m" } ?: "-" wikiDistanceText = d?.let { f -> "${f}\u00A0m" } ?: "-"
}
// Beräkna direkt
LaunchedEffect(lat, lon) { recalcWikiDistance() }
// Lyssna på plats-tick för att uppdatera avståndet live
DisposableEffect(Unit) {
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
val receiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context?, intent: Intent?) { recalcWikiDistance() }
}
if (Build.VERSION.SDK_INT >= 33) {
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
} else {
@Suppress("DEPRECATION")
context.registerReceiver(receiver, filter)
}
onDispose { try { context.unregisterReceiver(receiver) } catch (_: Exception) {} }
} }
LaunchedEffect(pageId) { LaunchedEffect(pageId) {
@@ -169,35 +154,18 @@ fun FornsokDialog(
val platLat = item.lat val platLat = item.lat
val platLon = item.lon val platLon = item.lon
// Avståndstext som uppdateras på plats-tick // Avståndstext uppdateras via KMP LocationService
var fornDistanceText by remember { mutableStateOf("-") } var fornDistanceText by remember { mutableStateOf("-") }
val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates() } val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates() }
val locService = remember { LocationServiceProvider.get() }
LaunchedEffect(Unit) { locService.start() }
fun recalcFornDistance() { val current = locService.location.collectAsState(initial = null)
val my = app.klottr.util.LastLocationStore.lastKnownLocation LaunchedEffect(current.value?.lat, current.value?.lon, platLat, platLon) {
val d = if (my != null) val gp = current.value
app.klottr.util.distanceMeters(my.latitude, my.longitude, platLat, platLon).roundToInt() val d = if (gp != null)
app.klottr.util.distanceMeters(gp.lat, gp.lon, platLat, platLon).roundToInt()
else null else null
fornDistanceText = d?.let { "$it\u00A0m" } ?: "-" fornDistanceText = d?.let { f -> "${f}\u00A0m" } ?: "-"
}
// Beräkna direkt
LaunchedEffect(platLat, platLon) { recalcFornDistance() }
// Lyssna på plats-tick
DisposableEffect(Unit) {
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
val receiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context?, intent: Intent?) { recalcFornDistance() }
}
if (Build.VERSION.SDK_INT >= 33) {
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
} else {
@Suppress("DEPRECATION")
context.registerReceiver(receiver, filter)
}
onDispose { try { context.unregisterReceiver(receiver) } catch (_: Exception) {} }
} }
@@ -275,42 +243,15 @@ fun DmDialog(
val showCoords = remember { SettingsStore.getShowCoordinates() } val showCoords = remember { SettingsStore.getShowCoordinates() }
fun recalcDmDistance() { fun recalcDmDistance() {
val my = app.klottr.location.LastLocationStore.lastKnown // Använd delad LastLocationStore.lastKnown val my = app.klottr.location.LastLocationStore.lastKnown.value
val d = my?.let { // Null-säker hantering val d = my?.let {
app.klottr.util.distanceMeters( app.klottr.util.distanceMeters(it.lat, it.lon, item.lat, item.lon).roundToInt()
it.lat, // GeoPoint.lat
it.lon, // GeoPoint.lon
item.lat,
item.lon
).roundToInt()
} }
dmDistanceText = d?.let { formatDistance(it) } ?: "-" dmDistanceText = d?.let { formatDistance(it) } ?: "-"
} }
LaunchedEffect(item.lat, item.lon) { recalcDmDistance() } LaunchedEffect(item.lat, item.lon) { recalcDmDistance() }
DisposableEffect(Unit) {
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
val receiver = object : BroadcastReceiver() {
override fun onReceive(ctx: Context?, intent: Intent?) {
recalcDmDistance()
}
}
if (Build.VERSION.SDK_INT >= 33) {
context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED)
} else {
@Suppress("DEPRECATION")
context.registerReceiver(receiver, filter)
}
onDispose {
try {
context.unregisterReceiver(receiver)
} catch (_: Exception) {
}
}
}
// Hämta miniatyr om vi har bild-URL // Hämta miniatyr om vi har bild-URL
LaunchedEffect(item.id) { LaunchedEffect(item.id) {
// Text (om uniqueId finns) // Text (om uniqueId finns)

View File

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

View File

@@ -1,7 +1,7 @@
package app.klottr.location package app.klottr.location
/** Android-implementationen håller bara ett volatilt fält. */ ///** Android-implementationen håller bara ett volatilt fält. */
actual object LastLocationStore { //actual object LastLocationStore {
@Volatile // @Volatile
actual var lastKnown: GeoPoint? = null // 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 package app.klottr.location
/** Delad platsstore: senaste kända position som enkel GeoPoint. */ ///** Delad platsstore: senaste kända position som enkel GeoPoint. */
expect object LastLocationStore { //expect object LastLocationStore {
var lastKnown: GeoPoint? // var lastKnown: GeoPoint?
} //}

View File

@@ -1,10 +1,10 @@
package app.klottr.location package app.klottr.location
/** Enkel delad platsmodell för KMP. */ ///** Enkel delad platsmodell för KMP. */
data class GeoPoint(val lat: Double, val lon: Double) //data class GeoPoint(val lat: Double, val lon: Double)
//
/** Gränssnitt för plattforms-specifik platsinhämtning. */ ///** Gränssnitt för plattforms-specifik platsinhämtning. */
interface LocationProvider { //interface LocationProvider {
/** Returnerar aktuell plats eller senaste kända, eller null vid fel/tidsutlöpning. */ // /** Returnerar aktuell plats eller senaste kända, eller null vid fel/tidsutlöpning. */
suspend fun currentOrLastKnown(): GeoPoint? // 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 package app.klottr.location
//
/** iOS-stub tills riktig plats läggs till. */ ///** iOS-stub tills riktig plats läggs till. */
object IosLocationProvider : LocationProvider { //object IosLocationProvider : LocationProvider {
override suspend fun currentOrLastKnown(): GeoPoint? = null // override suspend fun currentOrLastKnown(): GeoPoint? = null
} //}

View File

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