v0.0.3. Stabilare version med bättre uppfångning av positioner.
@@ -35,7 +35,7 @@ android {
|
|||||||
minSdk = 26
|
minSdk = 26
|
||||||
targetSdk = 35
|
targetSdk = 35
|
||||||
versionCode = 1
|
versionCode = 1
|
||||||
versionName = "0.0.1"
|
versionName = "0.0.3"
|
||||||
|
|
||||||
// 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")}\"")
|
||||||
|
|||||||
BIN
app/release/app-release.apk
Normal file
BIN
app/release/baselineProfiles/0/app-release.dm
Normal file
BIN
app/release/baselineProfiles/1/app-release.dm
Normal file
37
app/release/output-metadata.json
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
{
|
||||||
|
"version": 3,
|
||||||
|
"artifactType": {
|
||||||
|
"type": "APK",
|
||||||
|
"kind": "Directory"
|
||||||
|
},
|
||||||
|
"applicationId": "com.example.yorlik",
|
||||||
|
"variantName": "release",
|
||||||
|
"elements": [
|
||||||
|
{
|
||||||
|
"type": "SINGLE",
|
||||||
|
"filters": [],
|
||||||
|
"attributes": [],
|
||||||
|
"versionCode": 1,
|
||||||
|
"versionName": "0.0.3",
|
||||||
|
"outputFile": "app-release.apk"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"elementType": "File",
|
||||||
|
"baselineProfiles": [
|
||||||
|
{
|
||||||
|
"minApi": 28,
|
||||||
|
"maxApi": 30,
|
||||||
|
"baselineProfiles": [
|
||||||
|
"baselineProfiles/1/app-release.dm"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"minApi": 31,
|
||||||
|
"maxApi": 2147483647,
|
||||||
|
"baselineProfiles": [
|
||||||
|
"baselineProfiles/0/app-release.dm"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"minSdkVersionForDexing": 26
|
||||||
|
}
|
||||||
BIN
app/release/yorlik0.0.3.apk
Normal file
BIN
app/src/main/ic_launcher-playstore.png
Normal file
|
After Width: | Height: | Size: 151 KiB |
@@ -14,10 +14,12 @@ 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 kotlin.math.min
|
||||||
|
import android.util.Log
|
||||||
|
|
||||||
class LocationService : Service() {
|
class LocationService : Service() {
|
||||||
|
|
||||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||||
|
|
||||||
private var fused: FusedLocationProviderClient? = null
|
private var fused: FusedLocationProviderClient? = null
|
||||||
|
|
||||||
// Match & anti-spam
|
// Match & anti-spam
|
||||||
@@ -27,6 +29,7 @@ class LocationService : Service() {
|
|||||||
private var activeNoteId: Long? = null
|
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
|
||||||
|
|
||||||
// Adaptivt intervall
|
// Adaptivt intervall
|
||||||
private val BASE_INTERVAL = 15_000L
|
private val BASE_INTERVAL = 15_000L
|
||||||
@@ -67,6 +70,35 @@ 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
|
||||||
|
scope.launch {
|
||||||
|
val fusedLocal = fused
|
||||||
|
try {
|
||||||
|
val first = withTimeout(5000L) {
|
||||||
|
fusedLocal?.lastLocation?.await() // <-- FIX: vänta in Task<Location>
|
||||||
|
?: fusedLocal?.getCurrentLocation(
|
||||||
|
com.google.android.gms.location.Priority.PRIORITY_HIGH_ACCURACY,
|
||||||
|
null
|
||||||
|
)?.await()
|
||||||
|
}
|
||||||
|
first?.let { firstFix ->
|
||||||
|
val list = withContext(Dispatchers.IO) {
|
||||||
|
Geocache.getNearby(
|
||||||
|
lat = firstFix.latitude,
|
||||||
|
lon = firstFix.longitude,
|
||||||
|
radiusMeters = QUERY_RADIUS_M,
|
||||||
|
ttlMs = 0L // bypassa cache helt vid start
|
||||||
|
)
|
||||||
|
}
|
||||||
|
cachedNearby = list
|
||||||
|
maybeMatch(firstFix)
|
||||||
|
}
|
||||||
|
} catch (_: Exception) {
|
||||||
|
// Ignorera fel — vi försöker igen vid ordinarie uppdatering
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
startLocationUpdates(currentIntervalMs, currentMinDistM)
|
startLocationUpdates(currentIntervalMs, currentMinDistM)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,35 +138,64 @@ class LocationService : Service() {
|
|||||||
scope.launch {
|
scope.launch {
|
||||||
handleAntiSpamState(loc)
|
handleAntiSpamState(loc)
|
||||||
|
|
||||||
// 1) Hämta (eller återanvänd) punkter via geohash-cache (TTL 30 s)
|
// Hämta närliggande (med cache) + en gångs cache-bypass om tomt
|
||||||
cachedNearby = Geocache.getNearby(
|
try {
|
||||||
|
val list = withContext(Dispatchers.IO) {
|
||||||
|
Geocache.getNearby(
|
||||||
lat = loc.latitude,
|
lat = loc.latitude,
|
||||||
lon = loc.longitude,
|
lon = loc.longitude,
|
||||||
radiusMeters = QUERY_RADIUS_M,
|
radiusMeters = QUERY_RADIUS_M,
|
||||||
ttlMs = 30_000L
|
ttlMs = 30_000L
|
||||||
)
|
)
|
||||||
|
|
||||||
// 2) Om vi är nära någon sparad punkt och står still → accuracy boost
|
|
||||||
val nearest = nearestDistanceToAny(loc.latitude, loc.longitude, cachedNearby)
|
|
||||||
val speed = estimateSpeedMps(loc)
|
|
||||||
DebugState.speedMps.value = speed
|
|
||||||
|
|
||||||
if (nearest != null && nearest < 60.0 && speed < 1.0f) {
|
|
||||||
// Tillfälligt: inga rörelsekrav så att bättre fixar levereras även när man står still
|
|
||||||
if (currentMinDistM > 0f) startLocationUpdates(currentIntervalMs, 0f)
|
|
||||||
|
|
||||||
// Engångsfix med hög noggrannhet (Google Maps-likt beteende)
|
|
||||||
tryAccuracyBoostOnce()?.let { better ->
|
|
||||||
LastLocationStore.lastKnownLocation = better
|
|
||||||
// matcha direkt med den bättre fixen
|
|
||||||
maybeMatch(better)
|
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
// Normal match
|
// Skriv alltid över cachedNearby, även om list är tom
|
||||||
|
cachedNearby = list
|
||||||
|
|
||||||
|
// Om tomt — gör en cache-bypass för att undvika "fastnat tomt"-läge
|
||||||
|
if (list.isEmpty()) {
|
||||||
|
val fresh = withContext(Dispatchers.IO) {
|
||||||
|
Geocache.getNearby(
|
||||||
|
lat = loc.latitude,
|
||||||
|
lon = loc.longitude,
|
||||||
|
radiusMeters = QUERY_RADIUS_M,
|
||||||
|
ttlMs = 0L // bypassa cache
|
||||||
|
)
|
||||||
|
}
|
||||||
|
cachedNearby = fresh
|
||||||
|
}
|
||||||
|
|
||||||
|
// Matcha direkt mot det senaste
|
||||||
|
maybeMatch(loc)
|
||||||
|
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
Log.e("Yorlik", "getNearby failed", t)
|
||||||
|
// Behåll tidigare cachedNearby som fallback — matcha ändå
|
||||||
maybeMatch(loc)
|
maybeMatch(loc)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3) Anpassa intervall & minDistance utifrån fart + kontext
|
// Beräkna speed och närmaste avstånd EFTER att cachedNearby är uppdaterad
|
||||||
|
val speed = estimateSpeedMps(loc)
|
||||||
|
val nearest = nearestDistanceToAny(loc.latitude, loc.longitude, cachedNearby)
|
||||||
|
|
||||||
|
// Stilla? Sänk minDistance → försök boost → matcha ändå även om boost uteblir
|
||||||
|
if (speed < 0.5f) {
|
||||||
|
if (currentMinDistM > 0f) {
|
||||||
|
startLocationUpdates(currentIntervalMs, 0f)
|
||||||
|
}
|
||||||
|
val boosted = tryAccuracyBoostOnce()
|
||||||
|
if (boosted != null) {
|
||||||
|
LastLocationStore.lastKnownLocation = boosted
|
||||||
|
maybeMatch(boosted)
|
||||||
|
} else {
|
||||||
|
maybeMatch(loc)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Rör vi oss, matcha mot nuvarande position
|
||||||
|
maybeMatch(loc)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Anpassa intervall & minDistance utifrån fart + kontext
|
||||||
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
|
||||||
@@ -155,7 +216,6 @@ class LocationService : Service() {
|
|||||||
private suspend fun tryAccuracyBoostOnce(): Location? = withContext(Dispatchers.Main) {
|
private suspend fun tryAccuracyBoostOnce(): Location? = withContext(Dispatchers.Main) {
|
||||||
val fusedLocal = fused ?: return@withContext null
|
val fusedLocal = fused ?: return@withContext null
|
||||||
return@withContext try {
|
return@withContext try {
|
||||||
// Timeout-skydd via withTimeout
|
|
||||||
withTimeout(7_000L) {
|
withTimeout(7_000L) {
|
||||||
fusedLocal.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
|
fusedLocal.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY, null).await()
|
||||||
}
|
}
|
||||||
@@ -168,10 +228,11 @@ class LocationService : Service() {
|
|||||||
distanceMeters(loc.latitude, loc.longitude, n.a, n.o) <= ACTIVE_RADIUS_M
|
distanceMeters(loc.latitude, loc.longitude, n.a, n.o) <= ACTIVE_RADIUS_M
|
||||||
} ?: return
|
} ?: return
|
||||||
|
|
||||||
// Spärra plats tills vi lämnat >200 m
|
// Spärra plats tills vi lämnat >200 m (eller tills tidsfönster gått ut)
|
||||||
activeNoteId = hit.i
|
activeNoteId = hit.i
|
||||||
activeCenterLat = hit.a
|
activeCenterLat = hit.a
|
||||||
activeCenterLon = hit.o
|
activeCenterLon = hit.o
|
||||||
|
lastHitAtMs = System.currentTimeMillis()
|
||||||
|
|
||||||
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)
|
||||||
@@ -232,7 +293,8 @@ class LocationService : Service() {
|
|||||||
val lat = activeCenterLat ?: return
|
val lat = activeCenterLat ?: return
|
||||||
val lon = activeCenterLon ?: return
|
val lon = activeCenterLon ?: return
|
||||||
val d = distanceMeters(loc.latitude, loc.longitude, lat, lon)
|
val d = distanceMeters(loc.latitude, loc.longitude, lat, lon)
|
||||||
if (d > RESET_RADIUS_M) {
|
val tooOld = (System.currentTimeMillis() - lastHitAtMs) > 10 * 60_000L // 10 min
|
||||||
|
if (d > RESET_RADIUS_M || tooOld) {
|
||||||
activeNoteId = null
|
activeNoteId = null
|
||||||
activeCenterLat = null
|
activeCenterLat = null
|
||||||
activeCenterLon = null
|
activeCenterLon = null
|
||||||
@@ -240,9 +302,13 @@ class LocationService : Service() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onDestroy() {
|
override fun onDestroy() {
|
||||||
fused?.removeLocationUpdates(callback)
|
|
||||||
requestRunning = false
|
requestRunning = false
|
||||||
scope.cancel()
|
try { fused?.removeLocationUpdates(callback) } catch (_: Exception) { }
|
||||||
|
finally { fused = null }
|
||||||
|
|
||||||
|
try { scope.cancel() } catch (_: Exception) { }
|
||||||
|
try { stopForeground(true) } catch (_: Exception) { }
|
||||||
|
|
||||||
super.onDestroy()
|
super.onDestroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
package com.example.yorlik
|
package com.example.yorlik
|
||||||
|
|
||||||
import android.Manifest
|
import android.Manifest
|
||||||
|
import android.content.Intent
|
||||||
import android.net.Uri
|
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.provider.Settings
|
||||||
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.contract.ActivityResultContracts
|
import androidx.activity.result.contract.ActivityResultContracts
|
||||||
import androidx.compose.foundation.layout.*
|
import androidx.compose.foundation.layout.*
|
||||||
import androidx.compose.foundation.lazy.LazyColumn
|
import androidx.compose.foundation.lazy.LazyColumn
|
||||||
@@ -20,19 +22,19 @@ import androidx.compose.ui.platform.LocalContext
|
|||||||
import androidx.compose.ui.text.input.TextFieldValue
|
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.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.util.*
|
import com.example.yorlik.util.*
|
||||||
import com.example.yorlik.BuildConfig
|
|
||||||
import kotlinx.coroutines.launch
|
|
||||||
import kotlinx.coroutines.tasks.await
|
|
||||||
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.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.tasks.await
|
||||||
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
|
||||||
@@ -41,15 +43,61 @@ class MainActivity : ComponentActivity() {
|
|||||||
|
|
||||||
private lateinit var signInClient: GoogleSignInClient
|
private lateinit var signInClient: GoogleSignInClient
|
||||||
|
|
||||||
private val permissionLauncher = registerForActivityResult(
|
// Flagga för tvåsteg (BG efter FG)
|
||||||
ActivityResultContracts.RequestMultiplePermissions()
|
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>
|
||||||
|
|
||||||
|
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)
|
||||||
|
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"
|
||||||
|
)
|
||||||
|
|
||||||
|
if (locOk) {
|
||||||
startLocationService(this)
|
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)
|
||||||
|
}
|
||||||
|
pendingBgRequest = false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private val signInLauncher = registerForActivityResult(
|
bgPermissionLauncher =
|
||||||
ActivityResultContracts.StartActivityForResult()
|
registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
|
||||||
) { res ->
|
android.util.Log.d("YorlikPerm", "BG result granted=$granted")
|
||||||
|
// inget ytterligare krävs här; service kör redan om FG fanns
|
||||||
|
}
|
||||||
|
|
||||||
|
signInLauncher =
|
||||||
|
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 acct = task.getResult(ApiException::class.java)
|
||||||
@@ -58,40 +106,42 @@ class MainActivity : ComponentActivity() {
|
|||||||
if (Auth.idToken == null) {
|
if (Auth.idToken == null) {
|
||||||
android.widget.Toast.makeText(
|
android.widget.Toast.makeText(
|
||||||
this,
|
this,
|
||||||
"ID-token saknas – kontrollera WEB_CLIENT_ID i BuildConfig och på servern.",
|
"ID-token saknas – kontrollera WEB_CLIENT_ID (Web client) och SHA‑1 i Android‑klienterna.",
|
||||||
android.widget.Toast.LENGTH_LONG
|
android.widget.Toast.LENGTH_LONG
|
||||||
).show()
|
).show()
|
||||||
|
} else {
|
||||||
|
android.util.Log.d(
|
||||||
|
"YorlikAuth",
|
||||||
|
"Inloggad: ${acct.email} (tokenLen=${Auth.idToken?.length})"
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (_: Exception) {
|
} catch (e: Exception) {
|
||||||
// Ignorera – användaren avbröt eller fel
|
android.util.Log.e("YorlikAuth", "GoogleSignIn fel", e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
// Be om behörigheter (FG först; ev. BG i steg 2)
|
||||||
super.onCreate(savedInstanceState)
|
|
||||||
|
|
||||||
signInClient = Auth.signInClient(this)
|
|
||||||
Auth.refreshSilently(this) { /* ignorerar resultat här */ }
|
|
||||||
|
|
||||||
requestAllRuntimePermissions()
|
requestAllRuntimePermissions()
|
||||||
|
|
||||||
|
// Starta service direkt om FG redan finns
|
||||||
|
if (hasFgLocationPerms(this)) {
|
||||||
startLocationService(this)
|
startLocationService(this)
|
||||||
|
}
|
||||||
|
|
||||||
setContent {
|
setContent {
|
||||||
MaterialTheme {
|
MaterialTheme {
|
||||||
YorlikScreen(
|
YorlikScreen(
|
||||||
openSettings = { openAppSettings() },
|
openSettings = { openAppSettings() },
|
||||||
requestPerms = { requestAllRuntimePermissions() },
|
requestPerms = { requestAllRuntimePermissions() },
|
||||||
signIn = {
|
signIn = { signInLauncher.launch(signInClient.signInIntent) },
|
||||||
val intent = signInClient.signInIntent
|
|
||||||
signInLauncher.launch(intent)
|
|
||||||
},
|
|
||||||
signOut = { Auth.clear(this) }
|
signOut = { Auth.clear(this) }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- PERMISSION REQUESTS ----
|
||||||
private fun requestAllRuntimePermissions() {
|
private fun requestAllRuntimePermissions() {
|
||||||
val perms = mutableListOf(
|
val perms = mutableListOf(
|
||||||
Manifest.permission.ACCESS_FINE_LOCATION,
|
Manifest.permission.ACCESS_FINE_LOCATION,
|
||||||
@@ -100,35 +150,48 @@ 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
|
||||||
}
|
}
|
||||||
perms += Manifest.permission.ACCESS_BACKGROUND_LOCATION
|
|
||||||
permissionLauncher.launch(perms.toTypedArray())
|
// BG begärs separat efter FG (Android 10+)
|
||||||
|
pendingBgRequest = Build.VERSION.SDK_INT >= 29 && !hasBgLocationPerm(this)
|
||||||
|
|
||||||
|
fgPermissionLauncher.launch(perms.toTypedArray())
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun openAppSettings() {
|
private fun openAppSettings() {
|
||||||
val intent = android.content.Intent(
|
val intent = Intent(
|
||||||
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
||||||
Uri.parse("package:$packageName")
|
Uri.parse("package:$packageName")
|
||||||
).apply { addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK) }
|
).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }
|
||||||
startActivity(intent)
|
startActivity(intent)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- Hjälpfunktioner (utanför klassen) ----
|
||||||
|
|
||||||
private fun startLocationService(ctx: android.content.Context) {
|
private fun startLocationService(ctx: android.content.Context) {
|
||||||
val i = android.content.Intent(ctx, LocationService::class.java)
|
val i = Intent(ctx, LocationService::class.java)
|
||||||
ctx.startForegroundService(i)
|
ctx.startForegroundService(i)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Snabb koll av platsbehörigheter */
|
/** Endast foreground‑platsbehörigheter (räcker för UI + start av service) */
|
||||||
private fun hasLocationPerms(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
|
||||||
val coarse = ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_COARSE_LOCATION) ==
|
val coarse = ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_COARSE_LOCATION) ==
|
||||||
android.content.pm.PackageManager.PERMISSION_GRANTED
|
android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||||
val bg = ContextCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_BACKGROUND_LOCATION) ==
|
return fine || coarse
|
||||||
android.content.pm.PackageManager.PERMISSION_GRANTED
|
|
||||||
return (fine || coarse) && bg
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Bakgrundsbehörighet (Android 10+) – används för diagnos/valfri steg 2‑begäran */
|
||||||
|
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
|
@Composable
|
||||||
fun YorlikScreen(
|
fun YorlikScreen(
|
||||||
openSettings: () -> Unit,
|
openSettings: () -> Unit,
|
||||||
@@ -155,19 +218,17 @@ fun YorlikScreen(
|
|||||||
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) }
|
||||||
|
|
||||||
var permsGranted by remember { mutableStateOf(hasLocationPerms(context)) }
|
// UI kräver bara FG‑behörighet
|
||||||
|
var permsGranted by remember { mutableStateOf(hasFgLocationPerms(context)) }
|
||||||
var showPermDialog by remember { mutableStateOf(!permsGranted) }
|
var showPermDialog by remember { mutableStateOf(!permsGranted) }
|
||||||
|
|
||||||
val loggedIn by Auth.loggedIn.collectAsState()
|
val loggedIn by Auth.loggedIn.collectAsState()
|
||||||
val userEmail by Auth.emailFlow.collectAsState()
|
val userEmail by Auth.emailFlow.collectAsState()
|
||||||
|
|
||||||
LaunchedEffect(Unit) {
|
LaunchedEffect(Unit) {
|
||||||
// Försök återställa inloggning tyst; UI uppdateras via flödena i Auth
|
|
||||||
Auth.refreshSilently(context) { /* no-op */ }
|
Auth.refreshSilently(context) { /* no-op */ }
|
||||||
|
|
||||||
// Efter en kort stund: kolla platsbehörigheter och visa ev. dialog
|
|
||||||
kotlinx.coroutines.delay(1000)
|
kotlinx.coroutines.delay(1000)
|
||||||
permsGranted = hasLocationPerms(context)
|
permsGranted = hasFgLocationPerms(context)
|
||||||
showPermDialog = !permsGranted
|
showPermDialog = !permsGranted
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -326,10 +387,10 @@ fun YorlikScreen(
|
|||||||
PermissionDialog(
|
PermissionDialog(
|
||||||
onRequest = {
|
onRequest = {
|
||||||
requestPerms()
|
requestPerms()
|
||||||
// kolla igen
|
// kolla igen efter liten stund
|
||||||
scope.launch {
|
scope.launch {
|
||||||
kotlinx.coroutines.delay(1500)
|
kotlinx.coroutines.delay(1500)
|
||||||
val ok = hasLocationPerms(context)
|
val ok = hasFgLocationPerms(context)
|
||||||
showPermDialog = !ok
|
showPermDialog = !ok
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -12,19 +12,27 @@ import retrofit2.converter.moshi.MoshiConverterFactory
|
|||||||
import retrofit2.http.*
|
import retrofit2.http.*
|
||||||
import com.example.yorlik.util.Auth
|
import com.example.yorlik.util.Auth
|
||||||
import com.example.yorlik.BuildConfig
|
import com.example.yorlik.BuildConfig
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Läser bas‑URL och API‑nyckel från BuildConfig (hålls i local.properties → buildConfigField).
|
||||||
|
* Byt inte namn här – resten av appen förväntar sig NoteDTO/CreateBody/YorlikApi.
|
||||||
|
*/
|
||||||
object ApiConfig {
|
object ApiConfig {
|
||||||
val SERVER_API_BASE_URL: String get() = BuildConfig.SERVER_API_BASE_URL
|
val SERVER_API_BASE_URL: String get() = ensureTrailingSlash(BuildConfig.SERVER_API_BASE_URL)
|
||||||
val SERVER_API_KEY: String get() = BuildConfig.SERVER_API_KEY
|
val SERVER_API_KEY: String get() = BuildConfig.SERVER_API_KEY
|
||||||
|
|
||||||
|
private fun ensureTrailingSlash(u: String): String =
|
||||||
|
if (u.endsWith("/")) u else "$u/"
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Kompakta fält enligt nearby.php */
|
/** Kompakta fält enligt nearby.php (behållna som i v0.0.1) */
|
||||||
data class NoteDTO(
|
data class NoteDTO(
|
||||||
val i: Long, // id
|
val i: Long, // id
|
||||||
val a: Double, // lat
|
val a: Double, // lat
|
||||||
val o: Double, // lon
|
val o: Double, // lon
|
||||||
val t: String, // text
|
val t: String, // text
|
||||||
val c: Long, // createdAt
|
val c: Long, // createdAt (ms)
|
||||||
val u: String // updated_at (ISO)
|
val u: String // updated_at (ISO)
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -37,6 +45,7 @@ data class CreateBody(
|
|||||||
val userId: String? = null // fylls från Auth.userId (Google sub)
|
val userId: String? = null // fylls från Auth.userId (Google sub)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/** Dina endpoints – samma namn/banor som i v0.0.1 */
|
||||||
interface YorlikApi {
|
interface YorlikApi {
|
||||||
@POST("create.php")
|
@POST("create.php")
|
||||||
suspend fun create(@Body body: CreateBody): RResponse<Map<String, Any>>
|
suspend fun create(@Body body: CreateBody): RResponse<Map<String, Any>>
|
||||||
@@ -52,11 +61,13 @@ interface YorlikApi {
|
|||||||
): RResponse<List<NoteDTO>>
|
): RResponse<List<NoteDTO>>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Lägger API‑nyckel + ev. Google ID‑token (Bearer) på varje request. */
|
||||||
private class ApiKeyInterceptor : Interceptor {
|
private class ApiKeyInterceptor : Interceptor {
|
||||||
override fun intercept(chain: Interceptor.Chain): Response {
|
override fun intercept(chain: Interceptor.Chain): Response {
|
||||||
val b = chain.request().newBuilder()
|
val b = chain.request().newBuilder()
|
||||||
.header("X-API-Key", ApiConfig.SERVER_API_KEY)
|
.header("X-API-Key", ApiConfig.SERVER_API_KEY)
|
||||||
// Lägg med Google ID-token om vi har en (Bearer)
|
|
||||||
|
// Lägg med Google ID-token om vi har en (för server‑side verifikation)
|
||||||
Auth.idToken?.let { token ->
|
Auth.idToken?.let { token ->
|
||||||
b.header("Authorization", "Bearer $token")
|
b.header("Authorization", "Bearer $token")
|
||||||
}
|
}
|
||||||
@@ -64,51 +75,86 @@ private class ApiKeyInterceptor : Interceptor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Retrofit/OkHttp build – med timeouts och logg i debug. */
|
||||||
object Api {
|
object Api {
|
||||||
private val moshi = Moshi.Builder()
|
private val moshi: Moshi by lazy {
|
||||||
|
Moshi.Builder()
|
||||||
.addLast(KotlinJsonAdapterFactory())
|
.addLast(KotlinJsonAdapterFactory())
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
private val log = HttpLoggingInterceptor().apply {
|
|
||||||
level = HttpLoggingInterceptor.Level.BASIC
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private val client = OkHttpClient.Builder()
|
private val http: OkHttpClient by lazy {
|
||||||
|
OkHttpClient.Builder()
|
||||||
.addInterceptor(ApiKeyInterceptor())
|
.addInterceptor(ApiKeyInterceptor())
|
||||||
.addInterceptor(log)
|
.connectTimeout(10, TimeUnit.SECONDS)
|
||||||
|
.readTimeout(10, TimeUnit.SECONDS)
|
||||||
|
.writeTimeout(10, TimeUnit.SECONDS)
|
||||||
|
.also { b ->
|
||||||
|
if (BuildConfig.DEBUG) {
|
||||||
|
val log = HttpLoggingInterceptor()
|
||||||
|
log.level = HttpLoggingInterceptor.Level.BASIC
|
||||||
|
b.addInterceptor(log)
|
||||||
|
}
|
||||||
|
}
|
||||||
.build()
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
private val retrofit = Retrofit.Builder()
|
private val retrofit: Retrofit by lazy {
|
||||||
|
Retrofit.Builder()
|
||||||
.baseUrl(ApiConfig.SERVER_API_BASE_URL)
|
.baseUrl(ApiConfig.SERVER_API_BASE_URL)
|
||||||
.client(client)
|
.client(http)
|
||||||
.addConverterFactory(MoshiConverterFactory.create(moshi))
|
.addConverterFactory(MoshiConverterFactory.create(moshi))
|
||||||
.build()
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
val svc: YorlikApi = retrofit.create(YorlikApi::class.java)
|
val svc: YorlikApi = retrofit.create(YorlikApi::class.java)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Resultatcontainer för cache/ETag‑flödet. */
|
||||||
data class NearbyResult(
|
data class NearbyResult(
|
||||||
val code: Int,
|
val code: Int, // HTTP‑kod (200, 304, etc.)
|
||||||
val items: List<NoteDTO>,
|
val items: List<NoteDTO>, // tom lista om 304/inga nya
|
||||||
val etag: String?
|
val etag: String? // serverns ETag (om någon)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hämtar nearby med stöd för ETag och "since".
|
||||||
|
* Kasta inte exception – returnera bara kod + lista + ny etag.
|
||||||
|
*/
|
||||||
suspend fun fetchNearby(
|
suspend fun fetchNearby(
|
||||||
lat: Double,
|
lat: Double,
|
||||||
lon: Double,
|
lon: Double,
|
||||||
radiusMeters: Int,
|
radiusMeters: Int,
|
||||||
sinceMs: Long,
|
sinceMs: Long,
|
||||||
lastEtag: String?
|
lastEtag: String? = null,
|
||||||
|
limit: Int = 200
|
||||||
): NearbyResult {
|
): NearbyResult {
|
||||||
val resp = Api.svc.nearby(lat, lon, radiusMeters, sinceMs, 200, lastEtag)
|
val resp = try {
|
||||||
val newEtag = resp.headers()["ETag"]?.trim('"')
|
Api.svc.nearby(
|
||||||
|
lat = lat,
|
||||||
|
lon = lon,
|
||||||
|
radiusMeters = radiusMeters,
|
||||||
|
sinceMs = sinceMs,
|
||||||
|
limit = limit,
|
||||||
|
etag = lastEtag
|
||||||
|
)
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
// Nätfel – presentera som “inga nya” men kod 599 (icke‑standard) för att kunna skilja i logik
|
||||||
|
return NearbyResult(code = 599, items = emptyList(), etag = lastEtag)
|
||||||
|
}
|
||||||
|
|
||||||
|
val newEtag = resp.headers()["ETag"] ?: lastEtag
|
||||||
|
val body = if (resp.isSuccessful) resp.body().orEmpty() else emptyList()
|
||||||
return NearbyResult(
|
return NearbyResult(
|
||||||
code = resp.code(),
|
code = resp.code(),
|
||||||
items = resp.body().orEmpty(),
|
items = body,
|
||||||
etag = newEtag
|
etag = newEtag
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Skapar en not – returnerar true om servern svarar { ok: true } och HTTP 200.
|
||||||
|
*/
|
||||||
suspend fun createNote(
|
suspend fun createNote(
|
||||||
lat: Double,
|
lat: Double,
|
||||||
lon: Double,
|
lon: Double,
|
||||||
@@ -119,6 +165,10 @@ suspend fun createNote(
|
|||||||
lat = lat, lon = lon, text = text, createdAt = createdAt,
|
lat = lat, lon = lon, text = text, createdAt = createdAt,
|
||||||
userId = Auth.userId // Google “sub” när inloggad (annars null)
|
userId = Auth.userId // Google “sub” när inloggad (annars null)
|
||||||
)
|
)
|
||||||
val resp = Api.svc.create(body)
|
val resp = try {
|
||||||
|
Api.svc.create(body)
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
return resp.isSuccessful && (resp.body()?.get("ok") == true)
|
return resp.isSuccessful && (resp.body()?.get("ok") == true)
|
||||||
}
|
}
|
||||||
@@ -1,122 +1,149 @@
|
|||||||
package com.example.yorlik.net
|
package com.example.yorlik.net
|
||||||
|
|
||||||
import kotlin.math.abs
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
import kotlin.math.floor
|
import kotlin.math.floor
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* En enkel geohash-baserad cache av nearby-svar per "ruta".
|
* Robust cache och hämtning av närliggande anslag.
|
||||||
* - Precision 7 ≈ ~150 m rutor.
|
*
|
||||||
* - 30 s TTL (kan överstyras).
|
* Offentlig API behålls: getNearby(lat, lon, radiusMeters, ttlMs)
|
||||||
* - Använder ETag + since mot servern för minimala nyttodata.
|
* - Returnerar alltid en lista (ev. tom) och KASTAR INTE.
|
||||||
|
* - Använder intern cache per "ruta" (~110 m) så UI/Service får stabila svar.
|
||||||
|
* - Vid nätfel: faller tillbaka till cache (om det finns).
|
||||||
|
* - Om första hämtet blir tomt: gör EN omfråga utan cache (force refresh).
|
||||||
*/
|
*/
|
||||||
object Geocache {
|
object Geocache {
|
||||||
private const val DEFAULT_TTL_MS = 30_000L
|
|
||||||
private const val GEOHASH_PREC = 7
|
|
||||||
|
|
||||||
private data class Entry(
|
private data class Entry(
|
||||||
var items: List<NoteDTO>,
|
val timeMs: Long,
|
||||||
var etag: String?,
|
val items: List<NoteDTO>,
|
||||||
var sinceMs: Long,
|
val etag: String?,
|
||||||
var fetchedAt: Long
|
val sinceMs: Long
|
||||||
)
|
)
|
||||||
|
|
||||||
private val map = HashMap<String, Entry>()
|
// Cache per “ruta” (~0.001 grad ≈ 111 m) + radius-bucket för att separera olika radier
|
||||||
|
private val cache = ConcurrentHashMap<String, Entry>()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Huvudmetod, kompatibel med v0.0.1.
|
||||||
|
*
|
||||||
|
* @param ttlMs hur länge vi litar på cache innan vi försöker hämta nytt
|
||||||
|
*/
|
||||||
suspend fun getNearby(
|
suspend fun getNearby(
|
||||||
lat: Double,
|
lat: Double,
|
||||||
lon: Double,
|
lon: Double,
|
||||||
radiusMeters: Int,
|
radiusMeters: Int,
|
||||||
ttlMs: Long = DEFAULT_TTL_MS
|
ttlMs: Long
|
||||||
): List<NoteDTO> {
|
): List<NoteDTO> = withContext(Dispatchers.IO) {
|
||||||
val tile = geohash(lat, lon, GEOHASH_PREC)
|
val key = keyFor(lat, lon, radiusMeters)
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
val existing = map[tile]
|
|
||||||
|
|
||||||
// Färsk cache? returnera direkt
|
// 1) Snabbträff i giltig cache
|
||||||
if (existing != null && now - existing.fetchedAt < ttlMs) {
|
cache[key]?.let { e ->
|
||||||
return existing.items
|
if ((now - e.timeMs) <= ttlMs) {
|
||||||
|
return@withContext e.items
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Annars hämta från servern med ETag/since
|
// 2) Försök hämta nytt med ETag/since om vi har det
|
||||||
val etag = existing?.etag
|
val prev = cache[key]
|
||||||
val since = existing?.sinceMs ?: 0L
|
val first = safeFetch(
|
||||||
val res = fetchNearby(lat, lon, radiusMeters, since, etag)
|
lat = lat,
|
||||||
|
lon = lon,
|
||||||
return when (res.code) {
|
radiusMeters = radiusMeters,
|
||||||
200 -> {
|
sinceMs = prev?.sinceMs ?: 0L,
|
||||||
// Uppdatera entry (öka since om vi fått nyare)
|
etag = prev?.etag
|
||||||
val newSince = if (res.items.isNotEmpty()) {
|
|
||||||
maxOf(since, res.items.maxOf { it.c })
|
|
||||||
} else since
|
|
||||||
map[tile] = Entry(
|
|
||||||
items = res.items,
|
|
||||||
etag = res.etag ?: etag,
|
|
||||||
sinceMs = newSince,
|
|
||||||
fetchedAt = now
|
|
||||||
)
|
)
|
||||||
res.items
|
|
||||||
}
|
// Hantera 304/not-modified och nätfel (kod 599 i fetchNearby)
|
||||||
304 -> {
|
val firstItems = when (first.code) {
|
||||||
// Inget nytt – ”förläng” bara entrys ålder om det fanns en
|
304 -> prev?.items.orEmpty()
|
||||||
if (existing != null) {
|
200 -> first.items
|
||||||
existing.fetchedAt = now
|
|
||||||
if (res.etag != null) existing.etag = res.etag
|
|
||||||
existing.items
|
|
||||||
} else {
|
|
||||||
emptyList()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else -> {
|
else -> {
|
||||||
// Server- eller nätfel – fall tillbaka till ev. gammal cache
|
// Nätfel/annat → fall tillbaka till cache om vi har något
|
||||||
existing?.items ?: emptyList()
|
return@withContext prev?.items.orEmpty()
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// -------------------------------------------------------------
|
|
||||||
// Minimal geohash-encoder (base32), tillräcklig för klientcache
|
|
||||||
// -------------------------------------------------------------
|
|
||||||
private val base32 = "0123456789bcdefghjkmnpqrstuvwxyz".toCharArray()
|
|
||||||
|
|
||||||
private fun geohash(lat: Double, lon: Double, precision: Int): String {
|
|
||||||
var minLat = -90.0
|
|
||||||
var maxLat = 90.0
|
|
||||||
var minLon = -180.0
|
|
||||||
var maxLon = 180.0
|
|
||||||
|
|
||||||
val result = StringBuilder()
|
|
||||||
var isEven = true
|
|
||||||
var bit = 0
|
|
||||||
var ch = 0
|
|
||||||
|
|
||||||
while (result.length < precision) {
|
|
||||||
if (isEven) {
|
|
||||||
val mid = (minLon + maxLon) / 2
|
|
||||||
if (lon > mid) {
|
|
||||||
ch = ch or (1 shl (4 - bit))
|
|
||||||
minLon = mid
|
|
||||||
} else {
|
|
||||||
maxLon = mid
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
val mid = (minLat + maxLat) / 2
|
|
||||||
if (lat > mid) {
|
|
||||||
ch = ch or (1 shl (4 - bit))
|
|
||||||
minLat = mid
|
|
||||||
} else {
|
|
||||||
maxLat = mid
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
isEven = !isEven
|
// Uppdatera cache efter första försöket
|
||||||
if (bit < 4) {
|
val firstSince = if (firstItems.isNotEmpty())
|
||||||
bit++
|
firstItems.maxOfOrNull { it.c } ?: (prev?.sinceMs ?: 0L)
|
||||||
} else {
|
else
|
||||||
result.append(base32[ch])
|
(prev?.sinceMs ?: 0L)
|
||||||
bit = 0
|
|
||||||
ch = 0
|
cache[key] = Entry(
|
||||||
|
timeMs = now,
|
||||||
|
items = firstItems,
|
||||||
|
etag = first.etag ?: prev?.etag,
|
||||||
|
sinceMs = firstSince
|
||||||
|
)
|
||||||
|
|
||||||
|
// 3) Om listan är tom: gör EN omfråga utan cache/since (force refresh)
|
||||||
|
if (firstItems.isEmpty()) {
|
||||||
|
val fresh = safeFetch(
|
||||||
|
lat = lat,
|
||||||
|
lon = lon,
|
||||||
|
radiusMeters = radiusMeters,
|
||||||
|
sinceMs = 0L,
|
||||||
|
etag = null
|
||||||
|
)
|
||||||
|
|
||||||
|
val items = when (fresh.code) {
|
||||||
|
200 -> fresh.items
|
||||||
|
304 -> prev?.items.orEmpty() // borde inte inträffa utan etag, men säkra ändå
|
||||||
|
else -> prev?.items.orEmpty()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val since = if (items.isNotEmpty())
|
||||||
|
items.maxOfOrNull { it.c } ?: firstSince
|
||||||
|
else firstSince
|
||||||
|
|
||||||
|
cache[key] = Entry(
|
||||||
|
timeMs = now,
|
||||||
|
items = items,
|
||||||
|
etag = fresh.etag ?: first.etag ?: prev?.etag,
|
||||||
|
sinceMs = since
|
||||||
|
)
|
||||||
|
|
||||||
|
return@withContext items
|
||||||
}
|
}
|
||||||
return result.toString()
|
|
||||||
|
return@withContext firstItems
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Skyddad fetch som aldrig kastar – använder Api.fetchNearby från din Api.kt
|
||||||
|
private suspend fun safeFetch(
|
||||||
|
lat: Double,
|
||||||
|
lon: Double,
|
||||||
|
radiusMeters: Int,
|
||||||
|
sinceMs: Long,
|
||||||
|
etag: String?
|
||||||
|
): NearbyResult = try {
|
||||||
|
fetchNearby(
|
||||||
|
lat = roundCoord(lat),
|
||||||
|
lon = roundCoord(lon),
|
||||||
|
radiusMeters = radiusMeters.coerceIn(50, 2000),
|
||||||
|
sinceMs = sinceMs,
|
||||||
|
lastEtag = etag,
|
||||||
|
limit = 200
|
||||||
|
)
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
NearbyResult(code = 599, items = emptyList(), etag = etag)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Samma avrundning som du redan använder i UI när du sparar
|
||||||
|
private fun roundCoord(v: Double): Double = ((v * 1e6).roundToInt() / 1e6)
|
||||||
|
|
||||||
|
// Bygg en nyckel av "ruta" (0.001 grad) + radius bucket (avrundad till närmaste 50 m)
|
||||||
|
private fun keyFor(lat: Double, lon: Double, radiusMeters: Int): String {
|
||||||
|
val cellLat = floor(lat * 1000.0) / 1000.0
|
||||||
|
val cellLon = floor(lon * 1000.0) / 1000.0
|
||||||
|
val r = ((radiusMeters + 25) / 50) * 50 // 0..2000 i steg om 50
|
||||||
|
return "${cellLat.format3()},${cellLon.format3()}|r=$r"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Double.format3(): String = String.format("%.3f", this)
|
||||||
}
|
}
|
||||||
|
|||||||
5
app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<background android:drawable="@color/ic_launcher_background"/>
|
||||||
|
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||||
|
</adaptive-icon>
|
||||||
5
app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<background android:drawable="@color/ic_launcher_background"/>
|
||||||
|
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||||
|
</adaptive-icon>
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
|
||||||
<background android:drawable="@drawable/ic_launcher_background" />
|
|
||||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
|
||||||
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
|
|
||||||
</adaptive-icon>
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
|
||||||
<background android:drawable="@drawable/ic_launcher_background" />
|
|
||||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
|
||||||
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
|
|
||||||
</adaptive-icon>
|
|
||||||
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.7 KiB |
BIN
app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp
Normal file
|
After Width: | Height: | Size: 3.2 KiB |
|
Before Width: | Height: | Size: 2.8 KiB After Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 982 B After Width: | Height: | Size: 1.0 KiB |
BIN
app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp
Normal file
|
After Width: | Height: | Size: 1.6 KiB |
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 1.9 KiB After Width: | Height: | Size: 2.3 KiB |
BIN
app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp
Normal file
|
After Width: | Height: | Size: 5.5 KiB |
|
Before Width: | Height: | Size: 3.8 KiB After Width: | Height: | Size: 4.7 KiB |
|
Before Width: | Height: | Size: 2.8 KiB After Width: | Height: | Size: 4.5 KiB |
BIN
app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp
Normal file
|
After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 5.8 KiB After Width: | Height: | Size: 8.7 KiB |
|
Before Width: | Height: | Size: 3.8 KiB After Width: | Height: | Size: 7.4 KiB |
BIN
app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp
Normal file
|
After Width: | Height: | Size: 25 KiB |
|
Before Width: | Height: | Size: 7.6 KiB After Width: | Height: | Size: 14 KiB |
4
app/src/main/res/values/ic_launcher_background.xml
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<color name="ic_launcher_background">#FFFFFF</color>
|
||||||
|
</resources>
|
||||||