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:
@@ -35,7 +35,7 @@ android {
|
|||||||
minSdk = 26
|
minSdk = 26
|
||||||
targetSdk = 35
|
targetSdk = 35
|
||||||
versionCode = 1
|
versionCode = 1
|
||||||
versionName = "0.0.3"
|
versionName = "0.0.4"
|
||||||
|
|
||||||
// BuildConfig-fält (åtkomst i Kotlin via BuildConfig.X)
|
// BuildConfig-fält (åtkomst i Kotlin via BuildConfig.X)
|
||||||
buildConfigField("String", "SERVER_API_BASE_URL", "\"${propOrEmpty("SERVER_API_BASE_URL")}\"")
|
buildConfigField("String", "SERVER_API_BASE_URL", "\"${propOrEmpty("SERVER_API_BASE_URL")}\"")
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import kotlinx.coroutines.*
|
|||||||
import kotlinx.coroutines.tasks.await
|
import kotlinx.coroutines.tasks.await
|
||||||
import kotlin.math.abs
|
import kotlin.math.abs
|
||||||
import kotlin.math.max
|
import kotlin.math.max
|
||||||
import kotlin.math.min
|
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
|
|
||||||
class LocationService : Service() {
|
class LocationService : Service() {
|
||||||
@@ -23,28 +22,25 @@ class LocationService : Service() {
|
|||||||
private var fused: FusedLocationProviderClient? = null
|
private var fused: FusedLocationProviderClient? = null
|
||||||
|
|
||||||
// Match & anti-spam
|
// 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 QUERY_RADIUS_M = 120 // fråga servern inom 120 m
|
||||||
private val RESET_RADIUS_M = 200.0
|
private val RESET_RADIUS_M = 200.0 // måste lämna >200 m för att samma ID ska kunna dingla igen
|
||||||
private var activeNoteId: Long? = null
|
|
||||||
private var activeCenterLat: Double? = null
|
private var activeCenterLat: Double? = null
|
||||||
private var activeCenterLon: 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
|
// Adaptivt intervall
|
||||||
private val BASE_INTERVAL = 15_000L
|
private val BASE_INTERVAL = 15_000L
|
||||||
private val WALK_INTERVAL = 5_000L
|
private var currentIntervalMs: Long = BASE_INTERVAL
|
||||||
private val JOG_INTERVAL = 2_000L
|
|
||||||
private val FAST_INTERVAL = 1_000L
|
|
||||||
|
|
||||||
// Minsta förflyttning
|
// Minsta förflyttning
|
||||||
private val BASE_MIN_DIST = 5f
|
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 currentMinDistM: Float = BASE_MIN_DIST
|
||||||
|
|
||||||
private var lastLocForSpeed: Location? = null
|
private var lastLocForSpeed: Location? = null
|
||||||
private var lastLocTimeMs: Long = 0L
|
private var lastLocTimeMs: Long = 0L
|
||||||
private var requestRunning = false
|
private var requestRunning = false
|
||||||
@@ -63,6 +59,14 @@ class LocationService : Service() {
|
|||||||
) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||||
if (!fineOk && !coarseOk) { stopSelf(); return }
|
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)
|
Notifications.createChannels(this)
|
||||||
startForeground(
|
startForeground(
|
||||||
Notifications.ONGOING_ID,
|
Notifications.ONGOING_ID,
|
||||||
@@ -71,12 +75,12 @@ class LocationService : Service() {
|
|||||||
|
|
||||||
fused = LocationServices.getFusedLocationProviderClient(this)
|
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 {
|
scope.launch {
|
||||||
val fusedLocal = fused
|
val fusedLocal = fused
|
||||||
try {
|
try {
|
||||||
val first = withTimeout(5000L) {
|
val first = withTimeout(5000L) {
|
||||||
fusedLocal?.lastLocation?.await() // <-- FIX: vänta in Task<Location>
|
fusedLocal?.lastLocation?.await()
|
||||||
?: fusedLocal?.getCurrentLocation(
|
?: fusedLocal?.getCurrentLocation(
|
||||||
com.google.android.gms.location.Priority.PRIORITY_HIGH_ACCURACY,
|
com.google.android.gms.location.Priority.PRIORITY_HIGH_ACCURACY,
|
||||||
null
|
null
|
||||||
@@ -88,14 +92,14 @@ class LocationService : Service() {
|
|||||||
lat = firstFix.latitude,
|
lat = firstFix.latitude,
|
||||||
lon = firstFix.longitude,
|
lon = firstFix.longitude,
|
||||||
radiusMeters = QUERY_RADIUS_M,
|
radiusMeters = QUERY_RADIUS_M,
|
||||||
ttlMs = 0L // bypassa cache helt vid start
|
ttlMs = 0L // bypassa cache vid start
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
cachedNearby = list
|
cachedNearby = list
|
||||||
maybeMatch(firstFix)
|
maybeMatch(firstFix)
|
||||||
}
|
}
|
||||||
} catch (_: Exception) {
|
} 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)
|
LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, intervalMs)
|
||||||
.setMinUpdateIntervalMillis(intervalMs)
|
.setMinUpdateIntervalMillis(intervalMs)
|
||||||
.setMinUpdateDistanceMeters(minDistanceM)
|
.setMinUpdateDistanceMeters(minDistanceM)
|
||||||
.setWaitForAccurateLocation(false) // Vi kör egen "boost" vid behov
|
.setWaitForAccurateLocation(false) // egen "boost" vid behov
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
private fun startLocationUpdates(intervalMs: Long, minDistanceM: Float) {
|
private fun startLocationUpdates(intervalMs: Long, minDistanceM: Float) {
|
||||||
@@ -165,7 +169,7 @@ class LocationService : Service() {
|
|||||||
cachedNearby = fresh
|
cachedNearby = fresh
|
||||||
}
|
}
|
||||||
|
|
||||||
// Matcha direkt mot det senaste
|
// Matcha direkt mot senaste datat
|
||||||
maybeMatch(loc)
|
maybeMatch(loc)
|
||||||
|
|
||||||
} catch (t: Throwable) {
|
} catch (t: Throwable) {
|
||||||
@@ -199,7 +203,7 @@ class LocationService : Service() {
|
|||||||
val desiredInterval = desiredIntervalForSpeed(speed)
|
val desiredInterval = desiredIntervalForSpeed(speed)
|
||||||
val desiredMinDist = desiredMinDistanceForContext(speed, nearest)
|
val desiredMinDist = desiredMinDistanceForContext(speed, nearest)
|
||||||
val intervalChanged = abs(desiredInterval - currentIntervalMs) >= 500L
|
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) {
|
if (intervalChanged || minDistChanged) {
|
||||||
startLocationUpdates(desiredInterval, desiredMinDist)
|
startLocationUpdates(desiredInterval, desiredMinDist)
|
||||||
} else {
|
} else {
|
||||||
@@ -222,24 +226,46 @@ class LocationService : Service() {
|
|||||||
} catch (_: Exception) { null }
|
} 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) {
|
private fun maybeMatch(loc: Location) {
|
||||||
if (activeNoteId != null) return
|
// Kandidater inom 20 m
|
||||||
val hit = cachedNearby.firstOrNull { n ->
|
val candidates = cachedNearby
|
||||||
distanceMeters(loc.latitude, loc.longitude, n.a, n.o) <= ACTIVE_RADIUS_M
|
.asSequence()
|
||||||
} ?: return
|
.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)
|
if (candidates.isEmpty()) return
|
||||||
activeNoteId = hit.i
|
|
||||||
|
// 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
|
activeCenterLat = hit.a
|
||||||
activeCenterLon = hit.o
|
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()
|
val now = System.currentTimeMillis()
|
||||||
HitLog.add(hit.t, hit.a, hit.o, now)
|
HitLog.add(hit.t, hit.a, hit.o, now)
|
||||||
|
SeenHits.markSeen(this, hit.i)
|
||||||
|
|
||||||
// Meddela UI + notis
|
// 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))
|
val entity = 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))
|
MatchBus.emit(entity)
|
||||||
|
Notifications.showHit(this, entity)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun nearestDistanceToAny(lat: Double, lon: Double, items: List<NoteDTO>): Double? {
|
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) {
|
private fun handleAntiSpamState(loc: Location) {
|
||||||
val id = activeNoteId ?: return
|
val lat = activeCenterLat
|
||||||
val lat = activeCenterLat ?: return
|
val lon = activeCenterLon
|
||||||
val lon = activeCenterLon ?: return
|
if (lat == null || lon == null) return
|
||||||
val d = distanceMeters(loc.latitude, loc.longitude, lat, lon)
|
val d = distanceMeters(loc.latitude, loc.longitude, lat, lon)
|
||||||
val tooOld = (System.currentTimeMillis() - lastHitAtMs) > 10 * 60_000L // 10 min
|
if (d > RESET_RADIUS_M) {
|
||||||
if (d > RESET_RADIUS_M || tooOld) {
|
|
||||||
activeNoteId = null
|
|
||||||
activeCenterLat = null
|
activeCenterLat = null
|
||||||
activeCenterLon = null
|
activeCenterLon = null
|
||||||
|
suppressedIdsInZone.clear()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -309,6 +335,10 @@ class LocationService : Service() {
|
|||||||
try { scope.cancel() } catch (_: Exception) { }
|
try { scope.cancel() } catch (_: Exception) { }
|
||||||
try { stopForeground(true) } catch (_: Exception) { }
|
try { stopForeground(true) } catch (_: Exception) { }
|
||||||
|
|
||||||
|
// Avregistrera prefs-lyssnare
|
||||||
|
SettingsStore.unobserve(this, prefListener)
|
||||||
|
prefListener = null
|
||||||
|
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,10 +2,9 @@ package com.example.yorlik
|
|||||||
|
|
||||||
import android.Manifest
|
import android.Manifest
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.net.Uri
|
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.provider.Settings
|
import android.widget.Toast
|
||||||
import androidx.activity.ComponentActivity
|
import androidx.activity.ComponentActivity
|
||||||
import androidx.activity.compose.setContent
|
import androidx.activity.compose.setContent
|
||||||
import androidx.activity.result.ActivityResultLauncher
|
import androidx.activity.result.ActivityResultLauncher
|
||||||
@@ -19,71 +18,45 @@ import androidx.compose.runtime.collectAsState
|
|||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.text.input.TextFieldValue
|
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.core.content.ContextCompat
|
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.Geocache
|
||||||
import com.example.yorlik.net.NoteDTO
|
import com.example.yorlik.net.NoteDTO
|
||||||
import com.example.yorlik.net.createNote
|
import com.example.yorlik.net.createNote
|
||||||
|
import com.example.yorlik.ui.theme.YorlikTheme
|
||||||
import com.example.yorlik.util.*
|
import com.example.yorlik.util.*
|
||||||
import com.google.android.gms.auth.api.signin.GoogleSignIn
|
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.common.api.ApiException
|
||||||
import com.google.android.gms.location.LocationServices as GmsLocationServices
|
import com.google.android.gms.location.LocationServices as GmsLocationServices
|
||||||
import com.google.android.gms.location.Priority
|
import com.google.android.gms.location.Priority
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.tasks.await
|
import kotlinx.coroutines.tasks.await
|
||||||
|
import kotlin.math.roundToInt
|
||||||
import java.time.Instant
|
import java.time.Instant
|
||||||
import java.time.ZoneId
|
import java.time.ZoneId
|
||||||
import java.time.format.DateTimeFormatter
|
import java.time.format.DateTimeFormatter
|
||||||
|
|
||||||
class MainActivity : ComponentActivity() {
|
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>>
|
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>
|
private lateinit var bgPermissionLauncher: ActivityResultLauncher<String>
|
||||||
|
|
||||||
// 3) Google‑inloggning
|
|
||||||
private lateinit var signInLauncher: ActivityResultLauncher<Intent>
|
private lateinit var signInLauncher: ActivityResultLauncher<Intent>
|
||||||
|
|
||||||
|
private var pendingBgRequest: Boolean = false
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
|
|
||||||
// --- Init sign-in client
|
// FG + (ev) BG
|
||||||
signInClient = Auth.signInClient(this)
|
|
||||||
Auth.refreshSilently(this) { /* no-op */ }
|
|
||||||
|
|
||||||
// --- Registrera launchers (OBS: görs i onCreate)
|
|
||||||
fgPermissionLauncher =
|
fgPermissionLauncher =
|
||||||
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { grants ->
|
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
|
||||||
val fineOk = grants[Manifest.permission.ACCESS_FINE_LOCATION] == true
|
val fgOk = hasFgLocationPerms(this)
|
||||||
val coarseOk = grants[Manifest.permission.ACCESS_COARSE_LOCATION] == true
|
if (fgOk) {
|
||||||
val locOk = fineOk || coarseOk
|
ContextCompat.startForegroundService(
|
||||||
|
this,
|
||||||
val postNotifGranted = if (Build.VERSION.SDK_INT >= 33) {
|
Intent(this, LocationService::class.java)
|
||||||
grants[Manifest.permission.POST_NOTIFICATIONS] == true
|
|
||||||
} else true
|
|
||||||
|
|
||||||
android.util.Log.d(
|
|
||||||
"YorlikPerm",
|
|
||||||
"FG result locOk=$locOk post=$postNotifGranted pendingBg=$pendingBgRequest"
|
|
||||||
)
|
)
|
||||||
|
if (Build.VERSION.SDK_INT >= 29 && !hasBgLocationPerm(this) && pendingBgRequest) {
|
||||||
if (locOk) {
|
|
||||||
startLocationService(this)
|
|
||||||
// Be om BG i steg 2 om markerat och relevant
|
|
||||||
if (pendingBgRequest && Build.VERSION.SDK_INT >= 29 && !hasBgLocationPerm(this)) {
|
|
||||||
bgPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
|
bgPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
|
||||||
}
|
}
|
||||||
pendingBgRequest = false
|
pendingBgRequest = false
|
||||||
@@ -91,58 +64,39 @@ class MainActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bgPermissionLauncher =
|
bgPermissionLauncher =
|
||||||
registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
registerForActivityResult(ActivityResultContracts.RequestPermission()) {
|
||||||
android.util.Log.d("YorlikPerm", "BG result granted=$granted")
|
// no-op
|
||||||
// inget ytterligare krävs här; service kör redan om FG fanns
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Google Sign-In
|
||||||
signInLauncher =
|
signInLauncher =
|
||||||
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { res ->
|
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { res ->
|
||||||
val task = GoogleSignIn.getSignedInAccountFromIntent(res.data)
|
val task = GoogleSignIn.getSignedInAccountFromIntent(res.data)
|
||||||
try {
|
try {
|
||||||
val acct = task.getResult(ApiException::class.java)
|
val account = task.getResult(ApiException::class.java)
|
||||||
if (acct != null) {
|
if (account != null) Auth.save(this, account)
|
||||||
Auth.save(this, acct)
|
} catch (_: ApiException) {
|
||||||
if (Auth.idToken == null) {
|
// ignorera
|
||||||
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})"
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} 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 {
|
setContent {
|
||||||
MaterialTheme {
|
YorlikTheme {
|
||||||
YorlikScreen(
|
Surface(Modifier.fillMaxSize()) {
|
||||||
openSettings = { openAppSettings() },
|
MainScreen(
|
||||||
requestPerms = { requestAllRuntimePermissions() },
|
onRequestPermissions = { requestAllRuntimePerms() },
|
||||||
signIn = { signInLauncher.launch(signInClient.signInIntent) },
|
onLogin = {
|
||||||
signOut = { Auth.clear(this) }
|
val intent = Auth.signInClient(this).signInIntent
|
||||||
|
signInLauncher.launch(intent)
|
||||||
|
},
|
||||||
|
onLogout = { Auth.clear(this) }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ---- PERMISSION REQUESTS ----
|
private fun requestAllRuntimePerms() {
|
||||||
private fun requestAllRuntimePermissions() {
|
|
||||||
val perms = mutableListOf(
|
val perms = mutableListOf(
|
||||||
Manifest.permission.ACCESS_FINE_LOCATION,
|
Manifest.permission.ACCESS_FINE_LOCATION,
|
||||||
Manifest.permission.ACCESS_COARSE_LOCATION
|
Manifest.permission.ACCESS_COARSE_LOCATION
|
||||||
@@ -150,30 +104,13 @@ class MainActivity : ComponentActivity() {
|
|||||||
if (Build.VERSION.SDK_INT >= 33) {
|
if (Build.VERSION.SDK_INT >= 33) {
|
||||||
perms += Manifest.permission.POST_NOTIFICATIONS
|
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())
|
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) ----
|
// Hjälpare i denna fil (så vi slipper saknade imports)
|
||||||
|
|
||||||
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 {
|
private fun hasFgLocationPerms(ctx: android.content.Context): Boolean {
|
||||||
val fine = ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_FINE_LOCATION) ==
|
val fine = ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_FINE_LOCATION) ==
|
||||||
android.content.pm.PackageManager.PERMISSION_GRANTED
|
android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||||
@@ -182,85 +119,102 @@ private fun hasFgLocationPerms(ctx: android.content.Context): Boolean {
|
|||||||
return fine || coarse
|
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) {
|
return if (Build.VERSION.SDK_INT >= 29) {
|
||||||
ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_BACKGROUND_LOCATION) ==
|
ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_BACKGROUND_LOCATION) ==
|
||||||
android.content.pm.PackageManager.PERMISSION_GRANTED
|
android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||||
} else true
|
} else true
|
||||||
}
|
}
|
||||||
|
}
|
||||||
// ---- UI ----
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun YorlikScreen(
|
private fun MainScreen(
|
||||||
openSettings: () -> Unit,
|
onRequestPermissions: () -> Unit,
|
||||||
requestPerms: () -> Unit,
|
onLogin: () -> Unit,
|
||||||
signIn: () -> Unit,
|
onLogout: () -> Unit
|
||||||
signOut: () -> Unit
|
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
|
|
||||||
|
// UI-state
|
||||||
|
var showMap by remember { mutableStateOf(false) }
|
||||||
var showWrite by remember { mutableStateOf(false) }
|
var showWrite by remember { mutableStateOf(false) }
|
||||||
var showPlaces by remember { mutableStateOf(false) }
|
var showPlaces by remember { mutableStateOf(false) }
|
||||||
var showMap by remember { mutableStateOf(false) }
|
var places by remember { mutableStateOf(emptyList<NoteDTO>()) }
|
||||||
|
|
||||||
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 placesLoading by remember { mutableStateOf(false) }
|
var placesLoading by remember { mutableStateOf(false) }
|
||||||
var placesError by remember { mutableStateOf<String?>(null) }
|
var placesError by remember { mutableStateOf<String?>(null) }
|
||||||
|
|
||||||
// UI kräver bara FG‑behörighet
|
// Inloggning från util/Auth.kt
|
||||||
var permsGranted by remember { mutableStateOf(hasFgLocationPerms(context)) }
|
val loggedIn by Auth.loggedIn.collectAsState(initial = false)
|
||||||
var showPermDialog by remember { mutableStateOf(!permsGranted) }
|
|
||||||
|
|
||||||
val loggedIn by Auth.loggedIn.collectAsState()
|
// Senaste träff – från util/Geo.kt (MatchBus.match)
|
||||||
val userEmail by Auth.emailFlow.collectAsState()
|
val lastMatch by MatchBus.match.collectAsState(initial = null)
|
||||||
|
|
||||||
LaunchedEffect(Unit) {
|
// Debug från util/Debug.kt
|
||||||
Auth.refreshSilently(context) { /* no-op */ }
|
val intervalMs by DebugState.intervalMs.collectAsState()
|
||||||
kotlinx.coroutines.delay(1000)
|
val minDistM by DebugState.minDistanceM.collectAsState()
|
||||||
permsGranted = hasFgLocationPerms(context)
|
val speedMps by DebugState.speedMps.collectAsState()
|
||||||
showPermDialog = !permsGranted
|
|
||||||
}
|
|
||||||
|
|
||||||
Surface(Modifier.fillMaxSize()) {
|
|
||||||
Column(
|
Column(
|
||||||
Modifier
|
Modifier
|
||||||
.fillMaxSize()
|
.fillMaxSize()
|
||||||
.padding(16.dp),
|
.windowInsetsPadding(WindowInsets.statusBars) // lämnar utrymme för systemfält
|
||||||
|
.padding(12.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(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)) {
|
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||||
Button(onClick = { showWrite = true }, enabled = loggedIn) { Text("Skriv") }
|
Button(onClick = { showWrite = true }) { Text("Klottra") }
|
||||||
|
|
||||||
if (!permsGranted) {
|
Button(onClick = {
|
||||||
OutlinedButton(onClick = openSettings) { Text("Behörigheter") }
|
// Ladda närliggande klotter (300 m)
|
||||||
}
|
placesLoading = true
|
||||||
OutlinedButton(onClick = {
|
placesError = null
|
||||||
placesLoading = true; placesError = null
|
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val loc = LastLocationStore.lastKnownLocation
|
val client = GmsLocationServices.getFusedLocationProviderClient(context)
|
||||||
?: run {
|
val loc = try {
|
||||||
try {
|
client.lastLocation.await()
|
||||||
val fused = GmsLocationServices.getFusedLocationProviderClient(context)
|
?: client.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
|
||||||
fused.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
|
|
||||||
} catch (_: Exception) { null }
|
} catch (_: Exception) { null }
|
||||||
}
|
|
||||||
if (loc == null) {
|
if (loc == null) {
|
||||||
placesLoading = false
|
placesLoading = false
|
||||||
placesError = "Ingen plats ännu – prova igen om en stund."
|
placesError = "Ingen plats ännu – prova igen."
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
val list = Geocache.getNearby(
|
val list = Geocache.getNearby(
|
||||||
@@ -268,55 +222,39 @@ fun YorlikScreen(
|
|||||||
radiusMeters = 300, ttlMs = 30_000L
|
radiusMeters = 300, ttlMs = 30_000L
|
||||||
)
|
)
|
||||||
places = list
|
places = list
|
||||||
showPlaces = true
|
|
||||||
placesLoading = false
|
placesLoading = false
|
||||||
|
showPlaces = true
|
||||||
}
|
}
|
||||||
}) { Text("Visa platser") }
|
}) { Text("Närliggande klotter") }
|
||||||
|
|
||||||
OutlinedButton(onClick = { showMap = true }) { Text("Karta") }
|
OutlinedButton(onClick = { showMap = true }) { Text("Karta") }
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inloggningsrad
|
// Senast
|
||||||
Row(
|
lastMatch?.let { m ->
|
||||||
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) {
|
|
||||||
ElevatedCard(Modifier.fillMaxWidth()) {
|
ElevatedCard(Modifier.fillMaxWidth()) {
|
||||||
Column(Modifier.padding(12.dp)) {
|
Column(Modifier.padding(12.dp)) {
|
||||||
Text("Senaste träff:", style = MaterialTheme.typography.titleMedium)
|
Text("Senast", style = MaterialTheme.typography.titleMedium)
|
||||||
Text(lastMatch!!.text)
|
Text(m.text)
|
||||||
Text(
|
Text("Lat: ${"%.5f".format(m.lat)} Lon: ${"%.5f".format(m.lon)}")
|
||||||
"(${lastMatch!!.lat}, ${lastMatch!!.lon})",
|
Text("Tid: ${formatTime(m.createdAt)}")
|
||||||
style = MaterialTheme.typography.bodySmall
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Debug
|
||||||
ElevatedCard(Modifier.fillMaxWidth()) {
|
ElevatedCard(Modifier.fillMaxWidth()) {
|
||||||
Column(Modifier.padding(12.dp)) {
|
Column(Modifier.padding(12.dp)) {
|
||||||
Text("Debug", style = MaterialTheme.typography.titleMedium)
|
Text("Debug", style = MaterialTheme.typography.titleMedium)
|
||||||
Text(
|
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()) {
|
if (hits.isEmpty()) {
|
||||||
Text("Inga träffar ännu.")
|
Text("Inga träffar ännu.")
|
||||||
} else {
|
} else {
|
||||||
@@ -333,40 +271,27 @@ fun YorlikScreen(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
// Dialoger
|
||||||
if (showWrite) {
|
if (showWrite) {
|
||||||
WriteDialog(
|
WriteDialog(
|
||||||
onDismiss = { showWrite = false },
|
onClose = { showWrite = false },
|
||||||
onSave = { text ->
|
onSave = { text ->
|
||||||
if (!loggedIn) {
|
val loc = LastLocationStore.lastKnownLocation
|
||||||
showInAppNotification("Logga in först.")
|
if (loc == null) {
|
||||||
|
Toast.makeText(context, "Ingen plats ännu – försök igen!", Toast.LENGTH_SHORT).show()
|
||||||
return@WriteDialog
|
return@WriteDialog
|
||||||
}
|
}
|
||||||
val ctx = context
|
scope.launch {
|
||||||
val scopeSave = scope
|
val ok = createNote(loc.latitude, loc.longitude, text, System.currentTimeMillis())
|
||||||
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())
|
|
||||||
if (!ok) {
|
if (!ok) {
|
||||||
showInAppNotification("Kunde inte spara till servern just nu.")
|
Toast.makeText(context, "Kunde inte spara till servern just nu.", Toast.LENGTH_SHORT).show()
|
||||||
return@launch
|
} else {
|
||||||
}
|
Toast.makeText(context, "Sparat.", Toast.LENGTH_SHORT).show()
|
||||||
showWrite = false
|
showWrite = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -383,61 +308,47 @@ fun YorlikScreen(
|
|||||||
MapDialog(onClose = { showMap = false })
|
MapDialog(onClose = { showMap = false })
|
||||||
}
|
}
|
||||||
|
|
||||||
if (showPermDialog) {
|
// Starta service om platsbehörighet redan finns
|
||||||
PermissionDialog(
|
LaunchedEffect(Unit) {
|
||||||
onRequest = {
|
val fine = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) ==
|
||||||
requestPerms()
|
android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||||
// kolla igen efter liten stund
|
val coarse = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) ==
|
||||||
scope.launch {
|
android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||||
kotlinx.coroutines.delay(1500)
|
if (fine || coarse) {
|
||||||
val ok = hasFgLocationPerms(context)
|
ContextCompat.startForegroundService(
|
||||||
showPermDialog = !ok
|
context,
|
||||||
}
|
Intent(context, LocationService::class.java)
|
||||||
},
|
|
||||||
onOpenSettings = openSettings,
|
|
||||||
onClose = { showPermDialog = false }
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
@Composable
|
||||||
private fun WriteDialog(
|
private fun WriteDialog(
|
||||||
onDismiss: () -> Unit,
|
onClose: () -> Unit,
|
||||||
onSave: (String) -> Unit
|
onSave: (String) -> Unit
|
||||||
) {
|
) {
|
||||||
var value by remember { mutableStateOf(TextFieldValue("")) }
|
var text by remember { mutableStateOf("") }
|
||||||
AlertDialog(
|
AlertDialog(
|
||||||
onDismissRequest = onDismiss,
|
onDismissRequest = onClose,
|
||||||
title = { Text("Ny text vid nuvarande plats") },
|
title = { Text("Klottra här") }, // <— ändrat från "Skriv anslag här"
|
||||||
text = {
|
text = {
|
||||||
Column {
|
Column {
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = value,
|
value = text,
|
||||||
onValueChange = { value = it },
|
onValueChange = { text = it },
|
||||||
label = { Text("Text") },
|
modifier = Modifier.fillMaxWidth().heightIn(min = 120.dp),
|
||||||
minLines = 3
|
placeholder = { Text("Din text…") }
|
||||||
)
|
|
||||||
Spacer(Modifier.height(8.dp))
|
|
||||||
Text(
|
|
||||||
"Sparas till servern med din nuvarande GPS-position.",
|
|
||||||
style = MaterialTheme.typography.bodySmall
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
confirmButton = {
|
confirmButton = {
|
||||||
Button(
|
Button(
|
||||||
onClick = { onSave(value.text.trim()) },
|
onClick = { onSave(text) },
|
||||||
enabled = value.text.isNotBlank()
|
enabled = text.isNotBlank()
|
||||||
) { Text("Spara") }
|
) { Text("Spara") }
|
||||||
},
|
},
|
||||||
dismissButton = { OutlinedButton(onClick = onDismiss) { Text("Avbryt") } }
|
dismissButton = { OutlinedButton(onClick = onClose) { Text("Avbryt") } }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -450,21 +361,39 @@ private fun PlacesDialog(
|
|||||||
) {
|
) {
|
||||||
AlertDialog(
|
AlertDialog(
|
||||||
onDismissRequest = onClose,
|
onDismissRequest = onClose,
|
||||||
title = { Text("Sparade platser (nära dig)") },
|
title = { Text("Närliggande klotter") },
|
||||||
text = {
|
text = {
|
||||||
Column(Modifier.fillMaxWidth().heightIn(max = 360.dp)) {
|
Column(Modifier.fillMaxWidth().heightIn(max = 360.dp)) {
|
||||||
when {
|
when {
|
||||||
loading -> Text("Laddar…")
|
loading -> Text("Laddar…")
|
||||||
error != null -> Text(error)
|
error != null -> Text(error)
|
||||||
items.isEmpty() -> Text("Inga platser i närheten.")
|
items.isEmpty() -> Text("Inga träffar i närheten.")
|
||||||
else -> {
|
else -> {
|
||||||
|
val ctx = LocalContext.current
|
||||||
|
val user = LastLocationStore.lastKnownLocation
|
||||||
LazyColumn {
|
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(
|
ListItem(
|
||||||
headlineContent = { Text(n.t) },
|
headlineContent = {
|
||||||
supportingContent = {
|
|
||||||
Text(
|
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
|
private fun formatTime(ms: Long): String {
|
||||||
fun PermissionDialog(
|
val z = ZoneId.systemDefault()
|
||||||
onRequest: () -> Unit,
|
val t = Instant.ofEpochMilli(ms).atZone(z)
|
||||||
onOpenSettings: () -> Unit,
|
return DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").format(t)
|
||||||
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") }
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|||||||
33
app/src/main/java/com/example/yorlik/util/SeenHits.kt
Normal file
33
app/src/main/java/com/example/yorlik/util/SeenHits.kt
Normal 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()
|
||||||
|
}
|
||||||
|
}
|
||||||
35
app/src/main/java/com/example/yorlik/util/SettingsStore.kt
Normal file
35
app/src/main/java/com/example/yorlik/util/SettingsStore.kt
Normal 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user