Yorlik 0.0.4. Nu heter det klotter istället för träffar. Bättre hantering av träffar (tjatar inte var 10:e minut). Möjlighet att stänga av så bara nytt klotter visas.

This commit is contained in:
2025-08-14 14:20:42 +02:00
parent 9135c33458
commit d20009d7f8
5 changed files with 362 additions and 348 deletions

View File

@@ -35,7 +35,7 @@ android {
minSdk = 26
targetSdk = 35
versionCode = 1
versionName = "0.0.3"
versionName = "0.0.4"
// BuildConfig-fält (åtkomst i Kotlin via BuildConfig.X)
buildConfigField("String", "SERVER_API_BASE_URL", "\"${propOrEmpty("SERVER_API_BASE_URL")}\"")

View File

@@ -13,7 +13,6 @@ import kotlinx.coroutines.*
import kotlinx.coroutines.tasks.await
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import android.util.Log
class LocationService : Service() {
@@ -23,28 +22,25 @@ class LocationService : Service() {
private var fused: FusedLocationProviderClient? = null
// Match & anti-spam
private val ACTIVE_RADIUS_M = 25.0 // snäppet större tolerans
private val NEW_HIT_RADIUS_M = 20.0 // nya träffar inom 20 m ska avisera direkt
private val QUERY_RADIUS_M = 120 // fråga servern inom 120 m
private val RESET_RADIUS_M = 200.0
private var activeNoteId: Long? = null
private val RESET_RADIUS_M = 200.0 // måste lämna >200 m för att samma ID ska kunna dingla igen
private var activeCenterLat: Double? = null
private var activeCenterLon: Double? = null
private var lastHitAtMs: Long = 0L // tidsbaserad reset
private val suppressedIdsInZone = mutableSetOf<Long>() // ID:n avis. i denna zon (nollas när vi lämnar >200 m)
// Inställning: endast nya träffar (kan växlas via SettingsStore)
@Volatile private var onlyNewHits: Boolean = false
private var prefListener: android.content.SharedPreferences.OnSharedPreferenceChangeListener? = null
// Adaptivt intervall
private val BASE_INTERVAL = 15_000L
private val WALK_INTERVAL = 5_000L
private val JOG_INTERVAL = 2_000L
private val FAST_INTERVAL = 1_000L
private var currentIntervalMs: Long = BASE_INTERVAL
// Minsta förflyttning
private val BASE_MIN_DIST = 5f
private val WALK_MIN_DIST = 2f
private val JOG_MIN_DIST = 1f
private val FAST_MIN_DIST = 0f
private var currentIntervalMs: Long = BASE_INTERVAL
private var currentMinDistM: Float = BASE_MIN_DIST
private var lastLocForSpeed: Location? = null
private var lastLocTimeMs: Long = 0L
private var requestRunning = false
@@ -63,6 +59,14 @@ class LocationService : Service() {
) == android.content.pm.PackageManager.PERMISSION_GRANTED
if (!fineOk && !coarseOk) { stopSelf(); return }
// Läs in inställning + lyssna på ändringar
onlyNewHits = SettingsStore.getOnlyNewHits(this)
prefListener = SettingsStore.observe(this) { key ->
if (key == SettingsStore.KEY_ONLY_NEW_HITS) {
onlyNewHits = SettingsStore.getOnlyNewHits(this)
}
}
Notifications.createChannels(this)
startForeground(
Notifications.ONGOING_ID,
@@ -71,12 +75,12 @@ class LocationService : Service() {
fused = LocationServices.getFusedLocationProviderClient(this)
// Direktmatch vid service-start – måste ligga efter fused-assign och före startLocationUpdates
// Direktmatch vid service-start – efter fused-assign och före startLocationUpdates
scope.launch {
val fusedLocal = fused
try {
val first = withTimeout(5000L) {
fusedLocal?.lastLocation?.await() // <-- FIX: vänta in Task<Location>
fusedLocal?.lastLocation?.await()
?: fusedLocal?.getCurrentLocation(
com.google.android.gms.location.Priority.PRIORITY_HIGH_ACCURACY,
null
@@ -88,14 +92,14 @@ class LocationService : Service() {
lat = firstFix.latitude,
lon = firstFix.longitude,
radiusMeters = QUERY_RADIUS_M,
ttlMs = 0L // bypassa cache helt vid start
ttlMs = 0L // bypassa cache vid start
)
}
cachedNearby = list
maybeMatch(firstFix)
}
} catch (_: Exception) {
// Ignorera fel — vi försöker igen vid ordinarie uppdatering
// Ignorera fel — ordinarie uppdateringar tar vid
}
}
@@ -106,7 +110,7 @@ class LocationService : Service() {
LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, intervalMs)
.setMinUpdateIntervalMillis(intervalMs)
.setMinUpdateDistanceMeters(minDistanceM)
.setWaitForAccurateLocation(false) // Vi kör egen "boost" vid behov
.setWaitForAccurateLocation(false) // egen "boost" vid behov
.build()
private fun startLocationUpdates(intervalMs: Long, minDistanceM: Float) {
@@ -165,7 +169,7 @@ class LocationService : Service() {
cachedNearby = fresh
}
// Matcha direkt mot det senaste
// Matcha direkt mot senaste datat
maybeMatch(loc)
} catch (t: Throwable) {
@@ -199,7 +203,7 @@ class LocationService : Service() {
val desiredInterval = desiredIntervalForSpeed(speed)
val desiredMinDist = desiredMinDistanceForContext(speed, nearest)
val intervalChanged = abs(desiredInterval - currentIntervalMs) >= 500L
val minDistChanged = abs(desiredMinDist - currentMinDistM) >= 0.5f
val minDistChanged = kotlin.math.abs(desiredMinDist - currentMinDistM) >= 0.5f
if (intervalChanged || minDistChanged) {
startLocationUpdates(desiredInterval, desiredMinDist)
} else {
@@ -222,24 +226,46 @@ class LocationService : Service() {
} catch (_: Exception) { null }
}
/**
* Match-logik:
* - Visa nya ID:n inom 20 m även om vi står kvar i zonen.
* - Visa aldrig samma ID igen förrän vi lämnat >200 m (hanteras av suppressedIdsInZone + reset).
* - Om "onlyNewHits" är aktivt: avisera bara ID:n som aldrig setts tidigare.
*/
private fun maybeMatch(loc: Location) {
if (activeNoteId != null) return
val hit = cachedNearby.firstOrNull { n ->
distanceMeters(loc.latitude, loc.longitude, n.a, n.o) <= ACTIVE_RADIUS_M
} ?: return
// Kandidater inom 20 m
val candidates = cachedNearby
.asSequence()
.filter { n -> distanceMeters(loc.latitude, loc.longitude, n.a, n.o) <= NEW_HIT_RADIUS_M }
// Filtrera bort sådana vi redan dinglat i den här zonen
.filter { n -> !suppressedIdsInZone.contains(n.i) }
// Respektera "endast nya träffar" om valt
.filter { n -> !onlyNewHits || !SeenHits.isSeen(this, n.i) }
.toList()
// Spärra plats tills vi lämnat >200 m (eller tills tidsfönster gått ut)
activeNoteId = hit.i
if (candidates.isEmpty()) return
// Ta närmaste (enkelt urval)
val hit = candidates.minBy { n -> distanceMeters(loc.latitude, loc.longitude, n.a, n.o) }
// Sätt zonens centrum när första träffen sker
if (activeCenterLat == null || activeCenterLon == null) {
activeCenterLat = hit.a
activeCenterLon = hit.o
lastHitAtMs = System.currentTimeMillis()
}
// Lägg ID i zonens "suppress"-mängd så det inte tjatar förrän vi lämnat >200 m
suppressedIdsInZone.add(hit.i)
// Logga träffen & markera som sedd
val now = System.currentTimeMillis()
HitLog.add(hit.t, hit.a, hit.o, now)
SeenHits.markSeen(this, hit.i)
// Meddela UI + notis
MatchBus.emit(com.example.yorlik.data.NoteEntity(id = hit.i, lat = hit.a, lon = hit.o, text = hit.t, createdAt = hit.c))
Notifications.showHit(this, com.example.yorlik.data.NoteEntity(id = hit.i, lat = hit.a, lon = hit.o, text = hit.t, createdAt = hit.c))
val entity = com.example.yorlik.data.NoteEntity(id = hit.i, lat = hit.a, lon = hit.o, text = hit.t, createdAt = hit.c)
MatchBus.emit(entity)
Notifications.showHit(this, entity)
}
private fun nearestDistanceToAny(lat: Double, lon: Double, items: List<NoteDTO>): Double? {
@@ -288,16 +314,16 @@ class LocationService : Service() {
}
}
/** Zon-reset: släpp allt bara när vi lämnat >200 m från zonens centrum. */
private fun handleAntiSpamState(loc: Location) {
val id = activeNoteId ?: return
val lat = activeCenterLat ?: return
val lon = activeCenterLon ?: return
val lat = activeCenterLat
val lon = activeCenterLon
if (lat == null || lon == null) return
val d = distanceMeters(loc.latitude, loc.longitude, lat, lon)
val tooOld = (System.currentTimeMillis() - lastHitAtMs) > 10 * 60_000L // 10 min
if (d > RESET_RADIUS_M || tooOld) {
activeNoteId = null
if (d > RESET_RADIUS_M) {
activeCenterLat = null
activeCenterLon = null
suppressedIdsInZone.clear()
}
}
@@ -309,6 +335,10 @@ class LocationService : Service() {
try { scope.cancel() } catch (_: Exception) { }
try { stopForeground(true) } catch (_: Exception) { }
// Avregistrera prefs-lyssnare
SettingsStore.unobserve(this, prefListener)
prefListener = null
super.onDestroy()
}

View File

@@ -2,10 +2,9 @@ package com.example.yorlik
import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.ActivityResultLauncher
@@ -19,71 +18,45 @@ import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import com.example.yorlik.BuildConfig
import com.example.yorlik.data.NoteEntity
import com.example.yorlik.net.Geocache
import com.example.yorlik.net.NoteDTO
import com.example.yorlik.net.createNote
import com.example.yorlik.ui.theme.YorlikTheme
import com.example.yorlik.util.*
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.location.LocationServices as GmsLocationServices
import com.google.android.gms.location.Priority
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
import kotlin.math.roundToInt
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
class MainActivity : ComponentActivity() {
private lateinit var signInClient: GoogleSignInClient
// Flagga för tvåsteg (BG efter FG)
private var pendingBgRequest: Boolean = false
// ---- LAUNCHERS ----
// 1) FG + (ev) notiser
private lateinit var fgPermissionLauncher: ActivityResultLauncher<Array<String>>
// 2) BG (separat för att undvika själv‑referens i init)
private lateinit var bgPermissionLauncher: ActivityResultLauncher<String>
// 3) Google‑inloggning
private lateinit var signInLauncher: ActivityResultLauncher<Intent>
private var pendingBgRequest: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// --- Init sign-in client
signInClient = Auth.signInClient(this)
Auth.refreshSilently(this) { /* no-op */ }
// --- Registrera launchers (OBS: görs i onCreate)
// FG + (ev) BG
fgPermissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { grants ->
val fineOk = grants[Manifest.permission.ACCESS_FINE_LOCATION] == true
val coarseOk = grants[Manifest.permission.ACCESS_COARSE_LOCATION] == true
val locOk = fineOk || coarseOk
val postNotifGranted = if (Build.VERSION.SDK_INT >= 33) {
grants[Manifest.permission.POST_NOTIFICATIONS] == true
} else true
android.util.Log.d(
"YorlikPerm",
"FG result locOk=$locOk post=$postNotifGranted pendingBg=$pendingBgRequest"
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
val fgOk = hasFgLocationPerms(this)
if (fgOk) {
ContextCompat.startForegroundService(
this,
Intent(this, LocationService::class.java)
)
if (locOk) {
startLocationService(this)
// Be om BG i steg 2 om markerat och relevant
if (pendingBgRequest && Build.VERSION.SDK_INT >= 29 && !hasBgLocationPerm(this)) {
if (Build.VERSION.SDK_INT >= 29 && !hasBgLocationPerm(this) && pendingBgRequest) {
bgPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
}
pendingBgRequest = false
@@ -91,58 +64,39 @@ class MainActivity : ComponentActivity() {
}
bgPermissionLauncher =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
android.util.Log.d("YorlikPerm", "BG result granted=$granted")
// inget ytterligare krävs här; service kör redan om FG fanns
registerForActivityResult(ActivityResultContracts.RequestPermission()) {
// no-op
}
// Google Sign-In
signInLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { res ->
val task = GoogleSignIn.getSignedInAccountFromIntent(res.data)
try {
val acct = task.getResult(ApiException::class.java)
if (acct != null) {
Auth.save(this, acct)
if (Auth.idToken == null) {
android.widget.Toast.makeText(
this,
"ID-token saknas – kontrollera WEB_CLIENT_ID (Web client) och SHA‑1 i Android‑klienterna.",
android.widget.Toast.LENGTH_LONG
).show()
} else {
android.util.Log.d(
"YorlikAuth",
"Inloggad: ${acct.email} (tokenLen=${Auth.idToken?.length})"
)
val account = task.getResult(ApiException::class.java)
if (account != null) Auth.save(this, account)
} catch (_: ApiException) {
// ignorera
}
}
} catch (e: Exception) {
android.util.Log.e("YorlikAuth", "GoogleSignIn fel", e)
}
}
// Be om behörigheter (FG först; ev. BG i steg 2)
requestAllRuntimePermissions()
// Starta service direkt om FG redan finns
if (hasFgLocationPerms(this)) {
startLocationService(this)
}
setContent {
MaterialTheme {
YorlikScreen(
openSettings = { openAppSettings() },
requestPerms = { requestAllRuntimePermissions() },
signIn = { signInLauncher.launch(signInClient.signInIntent) },
signOut = { Auth.clear(this) }
YorlikTheme {
Surface(Modifier.fillMaxSize()) {
MainScreen(
onRequestPermissions = { requestAllRuntimePerms() },
onLogin = {
val intent = Auth.signInClient(this).signInIntent
signInLauncher.launch(intent)
},
onLogout = { Auth.clear(this) }
)
}
}
}
}
// ---- PERMISSION REQUESTS ----
private fun requestAllRuntimePermissions() {
private fun requestAllRuntimePerms() {
val perms = mutableListOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
@@ -150,117 +104,117 @@ class MainActivity : ComponentActivity() {
if (Build.VERSION.SDK_INT >= 33) {
perms += Manifest.permission.POST_NOTIFICATIONS
}
// BG begärs separat efter FG (Android 10+)
pendingBgRequest = Build.VERSION.SDK_INT >= 29 && !hasBgLocationPerm(this)
fgPermissionLauncher.launch(perms.toTypedArray())
if (Build.VERSION.SDK_INT >= 29 && !hasBgLocationPerm(this)) {
pendingBgRequest = true
}
}
private fun openAppSettings() {
val intent = Intent(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:$packageName")
).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }
startActivity(intent)
}
}
// ---- Hjälpfunktioner (utanför klassen) ----
private fun startLocationService(ctx: android.content.Context) {
val i = Intent(ctx, LocationService::class.java)
ctx.startForegroundService(i)
}
/** Endast foreground‑platsbehörigheter (räcker för UI + start av service) */
private fun hasFgLocationPerms(ctx: android.content.Context): Boolean {
// Hjälpare i denna fil (så vi slipper saknade imports)
private fun hasFgLocationPerms(ctx: android.content.Context): Boolean {
val fine = ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_FINE_LOCATION) ==
android.content.pm.PackageManager.PERMISSION_GRANTED
val coarse = ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_COARSE_LOCATION) ==
android.content.pm.PackageManager.PERMISSION_GRANTED
return fine || coarse
}
}
/** Bakgrundsbehörighet (Android 10+) – används för diagnos/valfri steg 2‑begäran */
private fun hasBgLocationPerm(ctx: android.content.Context): Boolean {
private fun hasBgLocationPerm(ctx: android.content.Context): Boolean {
return if (Build.VERSION.SDK_INT >= 29) {
ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_BACKGROUND_LOCATION) ==
android.content.pm.PackageManager.PERMISSION_GRANTED
} else true
}
}
// ---- UI ----
@Composable
fun YorlikScreen(
openSettings: () -> Unit,
requestPerms: () -> Unit,
signIn: () -> Unit,
signOut: () -> Unit
private fun MainScreen(
onRequestPermissions: () -> Unit,
onLogin: () -> Unit,
onLogout: () -> Unit
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
// UI-state
var showMap by remember { mutableStateOf(false) }
var showWrite by remember { mutableStateOf(false) }
var showPlaces by remember { mutableStateOf(false) }
var showMap by remember { mutableStateOf(false) }
var lastMatch by remember { mutableStateOf<NoteEntity?>(null) }
MatchBus.match.collectAsState(null).value?.let { matched -> lastMatch = matched }
val intervalMs by DebugState.intervalMs.collectAsState()
val minDistM by DebugState.minDistanceM.collectAsState()
val speedMps by DebugState.speedMps.collectAsState()
val hits: List<HitEntry> by HitLog.entries.collectAsState()
var places by remember { mutableStateOf<List<NoteDTO>>(emptyList()) }
var places by remember { mutableStateOf(emptyList<NoteDTO>()) }
var placesLoading by remember { mutableStateOf(false) }
var placesError by remember { mutableStateOf<String?>(null) }
// UI kräver bara FG‑behörighet
var permsGranted by remember { mutableStateOf(hasFgLocationPerms(context)) }
var showPermDialog by remember { mutableStateOf(!permsGranted) }
// Inloggning från util/Auth.kt
val loggedIn by Auth.loggedIn.collectAsState(initial = false)
val loggedIn by Auth.loggedIn.collectAsState()
val userEmail by Auth.emailFlow.collectAsState()
// Senaste träff – från util/Geo.kt (MatchBus.match)
val lastMatch by MatchBus.match.collectAsState(initial = null)
LaunchedEffect(Unit) {
Auth.refreshSilently(context) { /* no-op */ }
kotlinx.coroutines.delay(1000)
permsGranted = hasFgLocationPerms(context)
showPermDialog = !permsGranted
}
// Debug från util/Debug.kt
val intervalMs by DebugState.intervalMs.collectAsState()
val minDistM by DebugState.minDistanceM.collectAsState()
val speedMps by DebugState.speedMps.collectAsState()
Surface(Modifier.fillMaxSize()) {
Column(
Modifier
.fillMaxSize()
.padding(16.dp),
.windowInsetsPadding(WindowInsets.statusBars) // lämnar utrymme för systemfält
.padding(12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Text("Yorlik (v${BuildConfig.VERSION_NAME})", style = MaterialTheme.typography.headlineMedium)
// Rubrik: Yorlik + version
Text(
text = "Yorlik v${BuildConfig.VERSION_NAME}",
style = MaterialTheme.typography.titleLarge
)
// Övre knapp-rad
// Toppknappar: Logga in / Behörigheter
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
if (loggedIn) {
OutlinedButton(onClick = onLogout) { Text("Logga ut") }
} else {
Button(onClick = onLogin) { Text("Logga in") }
}
OutlinedButton(onClick = onRequestPermissions) { Text("Behörigheter") }
}
// Checkbox: Avisera endast nya träffar
var onlyNew by remember { mutableStateOf(SettingsStore.getOnlyNewHits(context)) }
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text("Avisera endast nya träffar")
Switch(
checked = onlyNew,
onCheckedChange = {
onlyNew = it
SettingsStore.setOnlyNewHits(context, it)
}
)
}
// Åtgärdsknappar: Klottra / Närliggande klotter / Karta
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button(onClick = { showWrite = true }, enabled = loggedIn) { Text("Skriv") }
Button(onClick = { showWrite = true }) { Text("Klottra") }
if (!permsGranted) {
OutlinedButton(onClick = openSettings) { Text("Behörigheter") }
}
OutlinedButton(onClick = {
placesLoading = true; placesError = null
Button(onClick = {
// Ladda närliggande klotter (300 m)
placesLoading = true
placesError = null
scope.launch {
val loc = LastLocationStore.lastKnownLocation
?: run {
try {
val fused = GmsLocationServices.getFusedLocationProviderClient(context)
fused.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
val client = GmsLocationServices.getFusedLocationProviderClient(context)
val loc = try {
client.lastLocation.await()
?: client.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
} catch (_: Exception) { null }
}
if (loc == null) {
placesLoading = false
placesError = "Ingen plats ännu – prova igen om en stund."
placesError = "Ingen plats ännu – prova igen."
return@launch
}
val list = Geocache.getNearby(
@@ -268,55 +222,39 @@ fun YorlikScreen(
radiusMeters = 300, ttlMs = 30_000L
)
places = list
showPlaces = true
placesLoading = false
showPlaces = true
}
}) { Text("Visa platser") }
}) { Text("Närliggande klotter") }
OutlinedButton(onClick = { showMap = true }) { Text("Karta") }
}
// Inloggningsrad
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
if (loggedIn) {
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(userEmail ?: "Inloggad", style = MaterialTheme.typography.bodyMedium)
OutlinedButton(onClick = signOut) { Text("Logga ut") }
}
} else {
Button(onClick = signIn) { Text("Logga in") }
}
}
if (lastMatch != null) {
// Senast
lastMatch?.let { m ->
ElevatedCard(Modifier.fillMaxWidth()) {
Column(Modifier.padding(12.dp)) {
Text("Senaste träff:", style = MaterialTheme.typography.titleMedium)
Text(lastMatch!!.text)
Text(
"(${lastMatch!!.lat}, ${lastMatch!!.lon})",
style = MaterialTheme.typography.bodySmall
)
Text("Senast", style = MaterialTheme.typography.titleMedium)
Text(m.text)
Text("Lat: ${"%.5f".format(m.lat)} Lon: ${"%.5f".format(m.lon)}")
Text("Tid: ${formatTime(m.createdAt)}")
}
}
}
// Debug
ElevatedCard(Modifier.fillMaxWidth()) {
Column(Modifier.padding(12.dp)) {
Text("Debug", style = MaterialTheme.typography.titleMedium)
Text(
"Intervall: ${intervalMs / 1000}s • Min förflyttning: ${"%.1f".format(minDistM)} m • Hastighet: ${"%.1f".format(speedMps)} m/s"
"Intervall: ${intervalMs / 1000}s • MinDist: ${"%.1f".format(minDistM)} m • Hastighet: ${"%.1f".format(speedMps)} m/s"
)
}
}
Text("Logg över träffar:", style = MaterialTheme.typography.titleMedium)
// Funnet klotter (logg)
Text("Funnet klotter", style = MaterialTheme.typography.titleMedium)
val hits by HitLog.entries.collectAsState()
if (hits.isEmpty()) {
Text("Inga träffar ännu.")
} else {
@@ -333,40 +271,27 @@ fun YorlikScreen(
}
}
}
}
// Dialoger
if (showWrite) {
WriteDialog(
onDismiss = { showWrite = false },
onClose = { showWrite = false },
onSave = { text ->
if (!loggedIn) {
showInAppNotification("Logga in först.")
val loc = LastLocationStore.lastKnownLocation
if (loc == null) {
Toast.makeText(context, "Ingen plats ännu – försök igen!", Toast.LENGTH_SHORT).show()
return@WriteDialog
}
val ctx = context
val scopeSave = scope
scopeSave.launch {
var loc = LastLocationStore.lastKnownLocation
if (loc == null) {
try {
val fused = GmsLocationServices.getFusedLocationProviderClient(ctx)
loc = fused.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
} catch (_: Exception) { /* ignore */ }
}
if (loc == null) {
showInAppNotification("Ingen plats ännu – ge platsbehörighet och försök igen.")
return@launch
}
val lat = roundCoord(loc.latitude)
val lon = roundCoord(loc.longitude)
val ok = createNote(lat, lon, text, System.currentTimeMillis())
scope.launch {
val ok = createNote(loc.latitude, loc.longitude, text, System.currentTimeMillis())
if (!ok) {
showInAppNotification("Kunde inte spara till servern just nu.")
return@launch
}
Toast.makeText(context, "Kunde inte spara till servern just nu.", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(context, "Sparat.", Toast.LENGTH_SHORT).show()
showWrite = false
}
}
}
)
}
@@ -383,61 +308,47 @@ fun YorlikScreen(
MapDialog(onClose = { showMap = false })
}
if (showPermDialog) {
PermissionDialog(
onRequest = {
requestPerms()
// kolla igen efter liten stund
scope.launch {
kotlinx.coroutines.delay(1500)
val ok = hasFgLocationPerms(context)
showPermDialog = !ok
}
},
onOpenSettings = openSettings,
onClose = { showPermDialog = false }
// Starta service om platsbehörighet redan finns
LaunchedEffect(Unit) {
val fine = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) ==
android.content.pm.PackageManager.PERMISSION_GRANTED
val coarse = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) ==
android.content.pm.PackageManager.PERMISSION_GRANTED
if (fine || coarse) {
ContextCompat.startForegroundService(
context,
Intent(context, LocationService::class.java)
)
}
}
private fun formatTime(ms: Long): String {
val z = ZoneId.systemDefault()
val t = Instant.ofEpochMilli(ms)
val fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(z)
return fmt.format(t)
}
}
@Composable
private fun WriteDialog(
onDismiss: () -> Unit,
onClose: () -> Unit,
onSave: (String) -> Unit
) {
var value by remember { mutableStateOf(TextFieldValue("")) }
var text by remember { mutableStateOf("") }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Ny text vid nuvarande plats") },
onDismissRequest = onClose,
title = { Text("Klottra här") }, // <— ändrat från "Skriv anslag här"
text = {
Column {
OutlinedTextField(
value = value,
onValueChange = { value = it },
label = { Text("Text") },
minLines = 3
)
Spacer(Modifier.height(8.dp))
Text(
"Sparas till servern med din nuvarande GPS-position.",
style = MaterialTheme.typography.bodySmall
value = text,
onValueChange = { text = it },
modifier = Modifier.fillMaxWidth().heightIn(min = 120.dp),
placeholder = { Text("Din text…") }
)
}
},
confirmButton = {
Button(
onClick = { onSave(value.text.trim()) },
enabled = value.text.isNotBlank()
onClick = { onSave(text) },
enabled = text.isNotBlank()
) { Text("Spara") }
},
dismissButton = { OutlinedButton(onClick = onDismiss) { Text("Avbryt") } }
dismissButton = { OutlinedButton(onClick = onClose) { Text("Avbryt") } }
)
}
@@ -450,21 +361,39 @@ private fun PlacesDialog(
) {
AlertDialog(
onDismissRequest = onClose,
title = { Text("Sparade platser (nära dig)") },
title = { Text("Närliggande klotter") },
text = {
Column(Modifier.fillMaxWidth().heightIn(max = 360.dp)) {
when {
loading -> Text("Laddar…")
error != null -> Text(error)
items.isEmpty() -> Text("Inga platser i närheten.")
items.isEmpty() -> Text("Inga träffar i närheten.")
else -> {
val ctx = LocalContext.current
val user = LastLocationStore.lastKnownLocation
LazyColumn {
items(items) { n ->
items(items, key = { it.i }) { n ->
val distM = user?.let { distanceMeters(it.latitude, it.longitude, n.a, n.o) }
val isNew = distM != null && distM <= 200.0 && !SeenHits.isSeen(ctx, n.i)
val canRead = distM != null && distM <= 20.0
ListItem(
headlineContent = { Text(n.t) },
supportingContent = {
headlineContent = {
Text(
"Skapad: ${formatTime(n.c)} • Lat: ${"%.5f".format(n.a)} Lon: ${"%.5f".format(n.o)}"
text = if (canRead) n.t else "(Okänt klotter)", // <— ändrat från "(låst)"
style = MaterialTheme.typography.bodyMedium
)
},
supportingContent = {
val distStr = distM?.let { "${it.roundToInt()} m" } ?: "–"
Text(
buildString {
append("Id: "); append(n.i)
if (isNew) append(" (ny)")
append(" • Avstånd: "); append(distStr)
append(" • Skapad: "); append(formatTime(n.c))
append(" • Lat: "); append("%.5f".format(n.a))
append(" Lon: "); append("%.5f".format(n.o))
}
)
}
)
@@ -479,21 +408,8 @@ private fun PlacesDialog(
)
}
@Composable
fun PermissionDialog(
onRequest: () -> Unit,
onOpenSettings: () -> Unit,
onClose: () -> Unit
) {
AlertDialog(
onDismissRequest = onClose,
title = { Text("Behörighet krävs") },
text = { Text("Appen behöver platsbehörighet för att fungera korrekt.") },
confirmButton = {
TextButton(onClick = onRequest) { Text("Ge behörighet") }
},
dismissButton = {
TextButton(onClick = onOpenSettings) { Text("Öppna inställningar") }
}
)
private fun formatTime(ms: Long): String {
val z = ZoneId.systemDefault()
val t = Instant.ofEpochMilli(ms).atZone(z)
return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").format(t)
}

View File

@@ -0,0 +1,33 @@
package com.example.yorlik.util
import android.content.Context
/**
* Lagrar vilka Note-ID:n som redan har visats som träff.
* Implementerat med SharedPreferences StringSet för enkelhet.
*/
object SeenHits {
private const val PREFS_NAME = "yorlik_seen_hits"
private const val KEY_SET = "seen_ids"
private fun prefs(ctx: Context) =
ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
fun isSeen(ctx: Context, id: Long): Boolean {
val set = prefs(ctx).getStringSet(KEY_SET, emptySet()) ?: emptySet()
return set.contains(id.toString())
}
fun markSeen(ctx: Context, id: Long) {
val p = prefs(ctx)
val set = (p.getStringSet(KEY_SET, emptySet()) ?: emptySet()).toMutableSet()
if (set.add(id.toString())) {
p.edit().putStringSet(KEY_SET, set).apply()
}
}
/** För felsökning / återställning - rensa listan */
fun clear(ctx: Context) {
prefs(ctx).edit().remove(KEY_SET).apply()
}
}

View File

@@ -0,0 +1,35 @@
package com.example.yorlik.util
import android.content.Context
import android.content.SharedPreferences
/**
* Enkel inställnings-hanterare via SharedPreferences.
* Nyckeln "only_new_hits" styr om vi bara ska avisera helt nya träffar.
*/
object SettingsStore {
const val KEY_ONLY_NEW_HITS = "only_new_hits"
private const val PREFS_NAME = "yorlik_settings"
private fun prefs(ctx: Context): SharedPreferences =
ctx.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
fun getOnlyNewHits(ctx: Context): Boolean =
prefs(ctx).getBoolean(KEY_ONLY_NEW_HITS, false)
fun setOnlyNewHits(ctx: Context, value: Boolean) {
prefs(ctx).edit().putBoolean(KEY_ONLY_NEW_HITS, value).apply()
}
/** Registrera en lyssnare för förändringar. Returnera lyssnaren så att den kan tas bort. */
fun observe(ctx: Context, onKeyChanged: (String?) -> Unit): SharedPreferences.OnSharedPreferenceChangeListener {
val p = prefs(ctx)
val l = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> onKeyChanged(key) }
p.registerOnSharedPreferenceChangeListener(l)
return l
}
fun unobserve(ctx: Context, listener: SharedPreferences.OnSharedPreferenceChangeListener?) {
if (listener != null) prefs(ctx).unregisterOnSharedPreferenceChangeListener(listener)
}
}