WIP: Add new location service, disable old.
Note: this commit does not compile
This commit is contained in:
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -95,7 +95,6 @@ import app.klottr.create.createNoteFlow
|
||||
import app.klottr.create.queueNoteDocOutbox
|
||||
import app.klottr.data.AppDatabase
|
||||
import app.klottr.data.NoteRepository
|
||||
import app.klottr.location.AndroidLocationProvider
|
||||
import app.klottr.nearby.FoundOpenAction // Delat åtgärds-ADT
|
||||
import app.klottr.nearby.NearbyBundleShared
|
||||
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.SettingsStore
|
||||
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.formatDistance
|
||||
import app.klottr.work.OutboxWorker
|
||||
import coil3.ImageLoader
|
||||
import coil3.compose.setSingletonImageLoaderFactory
|
||||
import coil3.toBitmap
|
||||
import com.google.android.gms.common.api.ApiException
|
||||
import com.google.android.gms.location.Priority
|
||||
// Maps replaced by platform-independent MapContainer
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -168,7 +165,6 @@ import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.util.UUID
|
||||
import kotlin.math.roundToInt
|
||||
import com.google.android.gms.location.LocationServices as GmsLocationServices
|
||||
import app.klottr.maps.CameraPosition as CrossCameraPosition
|
||||
import app.klottr.maps.LatLng as CrossLatLng
|
||||
import app.klottr.maps.MapController
|
||||
@@ -189,13 +185,14 @@ class MainActivity : ComponentActivity() {
|
||||
super.onCreate(savedInstanceState)
|
||||
KLog.setEnabled(BuildConfig.KLLOG_DEBUG) // Styr loggnivå via buildflagga
|
||||
app.klottr.prefs.KvPrefs.init(applicationContext)
|
||||
LocationServiceProvider.init(applicationContext)
|
||||
|
||||
// FG + (ev) BG platstillstånd
|
||||
fgPermissionLauncher =
|
||||
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
|
||||
val fgOk = hasFgLocationPerms(this)
|
||||
if (fgOk) {
|
||||
startService(Intent(this, LocationService::class.java))
|
||||
LocationServiceProvider.get().start()
|
||||
if (Build.VERSION.SDK_INT >= 29 && !hasBgLocationPerm(this) && pendingBgRequest) {
|
||||
bgPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
|
||||
}
|
||||
@@ -231,7 +228,7 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
// Starta LocationService direkt om vi redan har FG-platstillstånd
|
||||
if (hasFgLocationPerms(this)) {
|
||||
startService(Intent(this, LocationService::class.java))
|
||||
LocationServiceProvider.get().start()
|
||||
}
|
||||
|
||||
setContent {
|
||||
@@ -301,6 +298,9 @@ private fun KlottrAppShell(
|
||||
onLogin: () -> Unit,
|
||||
onLogout: () -> Unit
|
||||
) {
|
||||
val locService = remember { LocationServiceProvider.get() }
|
||||
LaunchedEffect(Unit) { locService.start() }
|
||||
val currentLoc = locService.location.collectAsState(initial = null)
|
||||
val context = LocalContext.current
|
||||
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) {
|
||||
val gp = AndroidLocationProvider.currentOrLastKnown(context) // Nytt: centraliserad plats
|
||||
val gp = LocationServiceProvider.get().current(highAccuracy = false)
|
||||
if (gp != null) {
|
||||
// Spara som "senaste kända" och uppdatera away-flaggor
|
||||
LastLocationStore.lastKnownLocation = android.location.Location("klottr").apply {
|
||||
latitude = gp.lat; longitude = gp.lon
|
||||
} // Nytt: spegla in i din befintliga store
|
||||
FoundStore.updateAwayFlags(gp.lat, gp.lon) // Oför: men nu med delad modell
|
||||
|
||||
// Tvinga omritning så att avstånd visas utan scroll
|
||||
LastLocationStore.lastKnownLocation = android.location.Location("kmp").apply {
|
||||
latitude = gp.lat
|
||||
longitude = gp.lon
|
||||
time = gp.timeMillis ?: System.currentTimeMillis()
|
||||
accuracy = (gp.accuracyMeters ?: 0.0).toFloat()
|
||||
}
|
||||
FoundStore.updateAwayFlags(gp.lat, gp.lon)
|
||||
locationTick++
|
||||
}
|
||||
}
|
||||
@@ -434,22 +434,18 @@ private fun KlottrAppShell(
|
||||
onDispose { app.klottr.prefs.KvPrefs.removeListener(kvListener) }
|
||||
}
|
||||
|
||||
|
||||
// Lyssna efter ACTION_LOCATION_TICK
|
||||
DisposableEffect(Unit) {
|
||||
val filter = IntentFilter(LocationService.ACTION_LOCATION_TICK)
|
||||
val receiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(ctx: Context?, intent: Intent?) {
|
||||
locationTick++ // tvinga Compose att rita om där vi läser detta värde
|
||||
// Lyssna på KMP LocationService-flöde istället för broadcast
|
||||
LaunchedEffect(currentLoc.value?.lat, currentLoc.value?.lon) {
|
||||
currentLoc.value?.let { gp ->
|
||||
LastLocationStore.lastKnownLocation = android.location.Location("kmp").apply {
|
||||
latitude = gp.lat
|
||||
longitude = gp.lon
|
||||
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) {
|
||||
if (!showWiki && !showDm && !showFornsok) return@LaunchedEffect
|
||||
|
||||
val gp = AndroidLocationProvider.currentOrLastKnown(context)
|
||||
val gp = LocationServiceProvider.get().current(highAccuracy = false)
|
||||
if (gp != null) {
|
||||
val anyNew = withContext(Dispatchers.IO) {
|
||||
scanAndMarkFound(
|
||||
@@ -496,7 +492,7 @@ private fun KlottrAppShell(
|
||||
if (anyNew) {
|
||||
forceEmptyFound = false // Sätt tillbaka visning efter “Glöm alla fynd”
|
||||
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
|
||||
val ctx = context
|
||||
scope.launch {
|
||||
val gp = AndroidLocationProvider.currentOrLastKnown(ctx)
|
||||
val gp = LocationServiceProvider.get().current(highAccuracy = false)
|
||||
if (gp == null) {
|
||||
nearbyLoading = false
|
||||
nearbyError = "Ingen plats ännu – prova igen."
|
||||
@@ -821,10 +817,7 @@ private fun KlottrAppShell(
|
||||
context.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED))
|
||||
|
||||
// 3) Be tjänsten göra en rescan
|
||||
context.startService(
|
||||
Intent(context, LocationService::class.java)
|
||||
.setAction(LocationService.ACTION_RESCAN_NOW)
|
||||
)
|
||||
// old Android service call removed (handled in shared layer)
|
||||
|
||||
// 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.
|
||||
@@ -837,7 +830,7 @@ private fun KlottrAppShell(
|
||||
fornsokRadius = fornsokRadius
|
||||
)
|
||||
scope.launch {
|
||||
val gp = AndroidLocationProvider.currentOrLastKnown(context)
|
||||
val gp = LocationServiceProvider.get().current(highAccuracy = false)
|
||||
if (gp != null) {
|
||||
val anyNew = withContext(Dispatchers.IO) {
|
||||
scanAndMarkFound(
|
||||
@@ -857,7 +850,7 @@ private fun KlottrAppShell(
|
||||
if (anyNew) {
|
||||
forceEmptyFound = false // Tillåt visning igen
|
||||
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) {
|
||||
loading = !prefilledFromCache
|
||||
|
||||
// Hämta ev. färsk plats (fallback LastLocationStore)
|
||||
val my = LastLocationStore.lastKnownLocation
|
||||
val fused = GmsLocationServices.getFusedLocationProviderClient(context)
|
||||
val current = try {
|
||||
fused.lastLocation.await()
|
||||
?: fused.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
// Hämta ev. färsk plats
|
||||
val my = LocationServiceProvider.get().current(highAccuracy = false)
|
||||
|
||||
val qLat = current?.latitude ?: my?.latitude
|
||||
val qLon = current?.longitude ?: my?.longitude
|
||||
val qLat = my?.lat
|
||||
val qLon = my?.lon
|
||||
|
||||
// --- 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
|
||||
|
||||
@@ -4,7 +4,6 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.WorkerParameters
|
||||
import app.klottr.LocationService
|
||||
import app.klottr.net.Geocache
|
||||
import app.klottr.net.createNote
|
||||
import app.klottr.net.createNoteDoc
|
||||
@@ -146,7 +145,7 @@ class OutboxWorker(
|
||||
)
|
||||
|
||||
// Pinga UI så “Senaste” uppdateras direkt
|
||||
ctx.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED))
|
||||
// ctx.sendBroadcast(Intent(LocationService.ACTION_FOUND_UPDATED))
|
||||
}
|
||||
} catch (_: Throwable) {
|
||||
// Tyst fallback – Workern ska inte krascha pga visuell uppdatering
|
||||
|
||||
@@ -17,6 +17,7 @@ import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
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.mutableStateOf
|
||||
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.unit.dp
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import app.klottr.LocationService
|
||||
import app.klottr.net.DigitaltMuseumItem
|
||||
import app.klottr.net.FornsokItem
|
||||
import app.klottr.net.Wikipedia
|
||||
import app.klottr.location.LocationServiceProvider
|
||||
import app.klottr.util.SettingsStore
|
||||
import app.klottr.util.formatCoords
|
||||
import app.klottr.util.formatDistance
|
||||
@@ -54,34 +55,18 @@ fun WikiArticleDialog(
|
||||
var title 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("-") }
|
||||
val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates() }
|
||||
|
||||
fun recalcWikiDistance() {
|
||||
val my = app.klottr.util.LastLocationStore.lastKnownLocation
|
||||
val d = if (lat != null && lon != null && my != null)
|
||||
app.klottr.util.distanceMeters(my.latitude, my.longitude, lat, lon).roundToInt()
|
||||
val locService = remember { LocationServiceProvider.get() }
|
||||
LaunchedEffect(Unit) { locService.start() }
|
||||
val current = locService.location.collectAsState(initial = null)
|
||||
LaunchedEffect(current.value?.lat, current.value?.lon, lat, lon) {
|
||||
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
|
||||
wikiDistanceText = d?.let { "$it\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) {} }
|
||||
wikiDistanceText = d?.let { f -> "${f}\u00A0m" } ?: "-"
|
||||
}
|
||||
|
||||
LaunchedEffect(pageId) {
|
||||
@@ -169,35 +154,18 @@ fun FornsokDialog(
|
||||
val platLat = item.lat
|
||||
val platLon = item.lon
|
||||
|
||||
// Avståndstext som uppdateras på plats-tick
|
||||
// Avståndstext uppdateras via KMP LocationService
|
||||
var fornDistanceText by remember { mutableStateOf("-") }
|
||||
val showCoords = remember { app.klottr.util.SettingsStore.getShowCoordinates() }
|
||||
|
||||
|
||||
fun recalcFornDistance() {
|
||||
val my = app.klottr.util.LastLocationStore.lastKnownLocation
|
||||
val d = if (my != null)
|
||||
app.klottr.util.distanceMeters(my.latitude, my.longitude, platLat, platLon).roundToInt()
|
||||
val locService = remember { LocationServiceProvider.get() }
|
||||
LaunchedEffect(Unit) { locService.start() }
|
||||
val current = locService.location.collectAsState(initial = null)
|
||||
LaunchedEffect(current.value?.lat, current.value?.lon, platLat, platLon) {
|
||||
val gp = current.value
|
||||
val d = if (gp != null)
|
||||
app.klottr.util.distanceMeters(gp.lat, gp.lon, platLat, platLon).roundToInt()
|
||||
else null
|
||||
fornDistanceText = d?.let { "$it\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) {} }
|
||||
fornDistanceText = d?.let { f -> "${f}\u00A0m" } ?: "-"
|
||||
}
|
||||
|
||||
|
||||
@@ -275,42 +243,15 @@ fun DmDialog(
|
||||
val showCoords = remember { SettingsStore.getShowCoordinates() }
|
||||
|
||||
fun recalcDmDistance() {
|
||||
val my = app.klottr.location.LastLocationStore.lastKnown // Använd delad LastLocationStore.lastKnown
|
||||
val d = my?.let { // Null-säker hantering
|
||||
app.klottr.util.distanceMeters(
|
||||
it.lat, // GeoPoint.lat
|
||||
it.lon, // GeoPoint.lon
|
||||
item.lat,
|
||||
item.lon
|
||||
).roundToInt()
|
||||
val my = app.klottr.location.LastLocationStore.lastKnown.value
|
||||
val d = my?.let {
|
||||
app.klottr.util.distanceMeters(it.lat, it.lon, item.lat, item.lon).roundToInt()
|
||||
}
|
||||
dmDistanceText = d?.let { formatDistance(it) } ?: "-"
|
||||
}
|
||||
|
||||
|
||||
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
|
||||
LaunchedEffect(item.id) {
|
||||
// Text (om uniqueId finns)
|
||||
|
||||
Reference in New Issue
Block a user