RF Sentinel (RFSentinel): free, open-source police detector app for Android. Spots police body cams, Flock ALPR cameras, AirTag trackers, Remote ID drones, smart glasses and fake cell towers from Bluetooth LE and WiFi. No root.
Kotlin airtagalprandroidandroid-autoanti-surveillancebluetooth-low-energybody-cameracounter-surveillancedrone-detectionflock-safetyimsi-catcher-detectorpolice-detectorpolice-scannerprivacyremote-idrtl-sdrsdrsurveillance-detectiontracker-detectionwifi
Shared map GPS (no restart between the main screen and the full screen map), precise start position, arrow on the route while guided, device distances in feet / miles, Start button never cut off
CIS-C0918523d6009e
diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.ktindex 4426efb..da45efe 100644--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt@@ -337,6 +337,7 @@ class MainActivity : AppCompatActivity() {private var startPadStart = 0private var startPadEnd = 0private var startMinWidth = 0+ private var startIconGravity = com.google.android.material.button.MaterialButton.ICON_GRAVITY_STARTprivate fun fitStartButton() {val b = binding.startStopButton@@ -346,21 +347,27 @@ class MainActivity : AppCompatActivity() {val icon = if (running) R.drawable.ic_car_stop else R.drawable.ic_car_playif (startIconPadding < 0) { // the button as the layout made itstartIconPadding = b.iconPadding; startPadStart = b.paddingStart; startPadEnd = b.paddingEnd; startMinWidth = b.minWidth+ startIconGravity = b.iconGravity}fun withWord() {- b.text = label; b.setIconResource(icon); b.iconPadding = startIconPadding+ b.text = label; b.setIconResource(icon); b.iconPadding = startIconPadding; b.iconGravity = startIconGravityb.setPaddingRelative(startPadStart, b.paddingTop, startPadEnd, b.paddingBottom); b.minWidth = startMinWidth}if (b.width == 0) { withWord(); return }val room = b.width - startPadStart - startPadEndval drawn = b.transformationMethod?.getTransformation(label, b)?.toString() ?: label- val textW = b.paint.measureText(drawn) + 2 * d+ // The measured width runs a little short of what the button really needs (letter spacing, its own insets): a+ // word that only just fits by the measure showed cut off ("ST"), so it must fit with some room to spare.+ val textW = b.paint.measureText(drawn) * 1.1f + 6 * dval iconW = (b.iconSize.takeIf { it > 0 } ?: (24 * d).toInt()) + startIconPaddingif (textW + iconW <= room) withWord()else if (textW <= room) { withWord(); b.icon = null }else {- b.text = ""; b.setIconResource(icon); b.iconPadding = 0- b.setPaddingRelative(0, b.paddingTop, 0, b.paddingBottom); b.minWidth = (48 * d).toInt()+ // The icon alone, in the middle of the button: "text start" gravity centres the icon with its text, here an+ // invisible zero-width one (with no text at all the button keeps the icon at its start).+ b.text = ""; b.setIconResource(icon); b.iconPadding = 0+ b.iconGravity = com.google.android.material.button.MaterialButton.ICON_GRAVITY_TEXT_START+ b.setPaddingRelative(startPadStart, b.paddingTop, startPadEnd, b.paddingBottom); b.minWidth = (48 * d).toInt()}}diff --git a/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt b/app/src/main/java/com/rfsentinel/app/RFSentinelApp.ktindex b523918..381a7a1 100644--- a/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt+++ b/app/src/main/java/com/rfsentinel/app/RFSentinelApp.kt@@ -54,6 +54,7 @@ class RFSentinelApp : Application() {override fun onActivityDestroyed(a: android.app.Activity) {}})NotificationHelper.createChannels(this)+ com.rfsentinel.app.detect.DeviceIntel.applyUnits(this)// A downloaded update is done with once the app starts again (installed, or given up on).appScope.launch { com.rfsentinel.app.util.UpdateInstaller.cleanUp(this@RFSentinelApp) }// A fresh process means no camera download is running: drop any leftover progress.diff --git a/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt b/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.ktindex b40cbda..34ded30 100644--- a/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt@@ -316,9 +316,31 @@ object DeviceIntel {return 10.0.pow((measuredAt1m - rssi) / 25.0).coerceIn(0.1, 300.0)}- fun formatDistance(m: Double): String = when {+ /** Device distances in feet (and miles past 1000 ft) instead of metres: Settings > General > Device distances ([applyUnits]). */+ @Volatile var imperial = false++ /** Reads the Device distances setting: metres, feet, or the phone's region (feet where miles are used). */+ fun applyUnits(context: android.content.Context, locale: java.util.Locale = java.util.Locale.getDefault()) {+ imperial = when (com.rfsentinel.app.util.Prefs.deviceUnits(context)) {+ "ft" -> true+ "m" -> false+ else -> locale.country.uppercase(java.util.Locale.ROOT) in setOf("US", "GB", "LR", "MM")+ }+ }++ fun formatDistance(m: Double): String = formatDistance(m, imperial)++ fun formatDistance(m: Double, feet: Boolean): String = if (!feet) when {m < 1 -> "< 1 m"m < 10 -> "~${m.roundToInt()} m"else -> "~${(m / 5).roundToInt() * 5} m"+ } else {+ val ft = m * 3.28084+ when {+ ft < 3 -> "< 3 ft"+ ft < 30 -> "~${ft.roundToInt()} ft"+ ft < 1000 -> "~${(ft / 10).roundToInt() * 10} ft"+ else -> "~" + String.format(java.util.Locale.US, "%.1f mi", m / 1609.344)+ }}}diff --git a/app/src/main/java/com/rfsentinel/app/nav/Navigator.kt b/app/src/main/java/com/rfsentinel/app/nav/Navigator.ktindex b2dcbb1..3af8e94 100644--- a/app/src/main/java/com/rfsentinel/app/nav/Navigator.kt+++ b/app/src/main/java/com/rfsentinel/app/nav/Navigator.kt@@ -134,7 +134,7 @@ object Navigator {private var paceFromAlong: Double? = nullprivate var paceFromAt = 0L- private val listener = LocationListenerCompat { onLocation(it) }+ private val listener = LocationListenerCompat { com.rfsentinel.app.ui.MapGps.offer(it); onLocation(it) }private val userAgent get() = "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME}"/** The route options chosen in Settings, for a route nobody has adjusted. */diff --git a/app/src/main/java/com/rfsentinel/app/nav/RouteSnap.kt b/app/src/main/java/com/rfsentinel/app/nav/RouteSnap.ktnew file mode 100644index 0000000..08f1975--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/nav/RouteSnap.kt@@ -0,0 +1,39 @@+package com.rfsentinel.app.nav++import kotlin.math.atan2+import kotlin.math.cos++/**+ * While guided, the arrow sits on the route, as navigation apps do: a phone's GPS is often 5 - 15 m off in town+ * (buildings, trees), which put the arrow on the other side of the road or on the pavement. A fix close enough to+ * the route, going its way, is drawn at its point on the route and turned along it; one further off (you really+ * left the route, or took a turn it doesn't) is drawn where it is. Pure; unit-tested.+ */+object RouteSnap {++ /** Within this of the route a fix is put on it... */+ const val SNAP_M = 25.0+ /** ...or within this when the fix itself says it is that rough (never further). */+ const val SNAP_MAX_M = 40.0+ /** Heading this far against the route: not on it (the other carriageway, a U-turn). */+ private const val AGAINST_DEG = 60.0++ data class Snapped(val lat: Double, val lon: Double, val bearingDeg: Double, val state: RouteProgress.State)++ /** The fix at ([lat], [lon]) put on [route], or null when it should be drawn where it is. */+ fun snap(route: Route, lat: Double, lon: Double, bearingDeg: Double?, accuracyM: Double?, last: RouteProgress.State?): Snapped? {+ if (route.size < 2) return null+ val s = RouteProgress.locate(route, lat, lon, bearingDeg, last)+ val limit = maxOf(SNAP_M, minOf((accuracyM ?: 0.0) * 1.5, SNAP_MAX_M))+ if (s.offM > limit) return null+ if (bearingDeg != null && (s.headingOffDeg ?: 0.0) > AGAINST_DEG) return null+ val (la, lo) = RouteProgress.pointAt(route, s.alongM)+ val ahead = RouteProgress.pointAt(route, (s.alongM + 5.0).coerceAtMost(route.lengthM))+ val behind = if (ahead == la to lo) RouteProgress.pointAt(route, (s.alongM - 5.0).coerceAtLeast(0.0)) else la to lo+ val to = if (ahead == la to lo) la to lo else ahead+ val dy = to.first - behind.first+ val dx = (to.second - behind.second) * cos(Math.toRadians(la))+ val bearing = if (dx == 0.0 && dy == 0.0) (bearingDeg ?: 0.0) else (Math.toDegrees(atan2(dx, dy)) + 360.0) % 360.0+ return Snapped(la, lo, bearing, s)+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.ktindex f27b535..04aa601 100644--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt@@ -204,6 +204,7 @@ class ScanForegroundService : Service() {}lastLocation = itlastFix = it+ com.rfsentinel.app.ui.MapGps.offer(it)TripRecorder.onLocation(it)checkKnownAlpr(it)cellMonitor?.onLocation(it)diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.ktindex 6de799b..4ef2096 100644--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt@@ -1239,6 +1239,30 @@ class SettingsActivity : AppCompatActivity() {})}+ /** Settings > General > Device distances: how far a device is guessed to be, in metres or feet. */+ private fun setupDeviceUnits() {+ val box = binding.sectionGeneral+ val title = android.widget.TextView(this).apply {+ text = "Device distances"; textSize = 14f+ setPadding(0, (10 * resources.displayMetrics.density).toInt(), 0, (2 * resources.displayMetrics.density).toInt())+ }+ box.addView(infoRow(title, "How far away a device is guessed to be, from its signal strength, on the list, the " ++ "device details, the alerts and the car screen. Automatic shows feet where the phone's region uses miles " ++ "(US, UK...) and metres elsewhere; feet turn into miles past 1000 ft. Only a rough guess either way: walls and " ++ "bodies weaken a signal."))+ val group = android.widget.RadioGroup(this)+ for ((key, text) in listOf("auto" to "Automatic", "m" to "Metres", "ft" to "Feet and miles")) {+ group.addView(android.widget.RadioButton(this).apply {+ id = View.generateViewId(); this.text = text; tag = key+ isChecked = Prefs.deviceUnits(this@SettingsActivity) == key+ })+ }+ group.setOnCheckedChangeListener { g, id ->+ g.findViewById<View>(id)?.tag?.let { Prefs.setDeviceUnits(this, it as String); com.rfsentinel.app.detect.DeviceIntel.applyUnits(this) }+ }+ box.addView(group)+ }+/** Settings > Map: what the map shows (moved here from the map's menu). Saved as you switch. */private fun setupMapSection() {setupMapProvider()@@ -2036,6 +2060,7 @@ class SettingsActivity : AppCompatActivity() {binding.autoCamerasSwitch.isChecked = Prefs.autoCameras(this)setupMapSection()setupNavSection()+ setupDeviceUnits()setupRadioSection()setupLiveExport()addDetails()diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.ktindex 436c07b..4df2e8c 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt@@ -3,7 +3,6 @@ package com.rfsentinel.app.uiimport android.annotation.SuppressLintimport android.content.Intentimport android.location.Location-import androidx.core.location.LocationListenerCompatimport android.location.LocationManagerimport android.os.Buildimport android.os.Bundle@@ -91,8 +90,6 @@ class MapFragment : Fragment() {const val ARG_EMBEDDED = "embedded"/** A failed camera download stays in the status line this long (the retry runs after a minute). */private const val CAMERA_FAIL_SHOWN_MS = 90_000L- private const val GPS_MOVING_MS = 1_000L- private const val GPS_PARKED_MS = 5_000L/** [MapStart]'s levels are the classic raster map's: the vector map's are this much lower. */private const val ZOOM_SHIFT = MapStart.VECTOR_SHIFT/** 3D: your arrow this far down the map (navigation apps: about 70 %), so you see more road ahead. */@@ -877,7 +874,7 @@ class MapFragment : Fragment() {val m = map ?: returnapplyMarker()if (!m.startPuck()) return- (lastFix ?: knownFix())?.let { m.pushFix(steady(it)) }+ (lastFix ?: knownFix())?.let { m.pushFix(steady(onRoute(it))) }applyMode(animate = false)}@@ -891,8 +888,6 @@ class MapFragment : Fragment() {return Location(fix).apply { lastBearing?.let { bearing = it } }}- private val gpsListener = LocationListenerCompat { fix -> rf?.safe("fix") { onFix(fix) } ?: onFix(fix) }-/** When the map was last touched (panned, pinched...): the auto-recenter counts from it. */private var touchedAt = 0L@@ -906,8 +901,7 @@ class MapFragment : Fragment() {com.rfsentinel.app.nav.SpeedLimits.Live.onFix(fix.latitude, fix.longitude, fix.speed)updateGauge()val m = map?.takeIf { it.puckOn } ?: return- m.pushFix(steady(fix))- adaptGpsRate(fix)+ m.pushFix(steady(onRoute(fix)))val kmh = if (fix.hasSpeed()) fix.speed * 3.6f else 0fval before = smoothKmhsmoothKmh = if (smoothKmh < 0f) kmh else smoothKmh * 0.7f + kmh * 0.3f@@ -925,6 +919,25 @@ class MapFragment : Fragment() {if ((drives && before < 0f) || (moved && (drives || Navigator.active))) { lastZoomTarget = target; applyMode(animate = true) }}+ private var snapState: com.rfsentinel.app.nav.RouteProgress.State? = null++ /** While guided and close to the route: the fix drawn on it, turned along it ([com.rfsentinel.app.nav.RouteSnap]); else as it is. */+ private fun onRoute(fix: Location): Location {+ val route = com.rfsentinel.app.nav.Navigator.route+ if (!Navigator.active || route == null) { snapState = null; return fix }+ val moving = fix.hasSpeed() && fix.speed >= HEADING_MIN_SPEED_MS && fix.hasBearing()+ val s = com.rfsentinel.app.nav.RouteSnap.snap(route, fix.latitude, fix.longitude, if (moving) fix.bearing.toDouble() else null,+ if (fix.hasAccuracy()) fix.accuracy.toDouble() else null, snapState?.takeIf { route === snappedRoute })+ snappedRoute = route+ if (s == null) { snapState = null; return fix }+ snapState = s.state+ return Location(fix).apply {+ latitude = s.lat; longitude = s.lon+ if (moving) bearing = s.bearingDeg.toFloat()+ }+ }+ private var snappedRoute: com.rfsentinel.app.nav.Route? = null+/** Zoom levels added for the turn coming up (only while guiding). */private fun turnBoost(): Double {val s = Navigator.state ?: return 0.0@@ -935,51 +948,25 @@ class MapFragment : Fragment() {// ---- Battery: the map's own GPS ---------------------------------------------------------------------/**- * The position arrow's GPS: a fix a second (2 m) while moving - smooth enough for driving -- * and every 5 s (10 m) after a minute parked. Runs only while the map is on screen (off with- * the screen, the app in the background, or the main screen's Map view turned off).+ * The position arrow's GPS is [MapGps], shared by every map: the small map on the main screen and the full screen+ * map use the same one, so switching between them doesn't restart it. It runs while a map is on screen and stops a+ * little after the last one goes.*/private var listening = false- private var gpsParked = false- private var stillSince = 0L+ private val mapGpsListener: (Location) -> Unit = { fix -> rf?.safe("fix") { onFix(fix) } ?: onFix(fix) }- @SuppressLint("MissingPermission")private fun startGps() {if (listening || !Permissions.granted(act, android.Manifest.permission.ACCESS_FINE_LOCATION)) return- val lm = act.getSystemService(android.content.Context.LOCATION_SERVICE) as LocationManager- val provider = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && lm.hasProvider(LocationManager.FUSED_PROVIDER))- LocationManager.FUSED_PROVIDER else LocationManager.GPS_PROVIDER- val ms = if (gpsParked) GPS_PARKED_MS else GPS_MOVING_MS- val meters = if (gpsParked) 10f else 2f- runCatching {- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {- val req = android.location.LocationRequest.Builder(ms)- .setQuality(android.location.LocationRequest.QUALITY_HIGH_ACCURACY)- .setMinUpdateDistanceMeters(meters)- .build()- lm.requestLocationUpdates(provider, req, act.mainExecutor, gpsListener)- } else lm.requestLocationUpdates(provider, ms, meters, gpsListener, Looper.getMainLooper())- listening = true- }+ listening = true+ MapGps.subscribe(act, mapGpsListener)}private fun stopGps() {if (!listening) return- runCatching { (act.getSystemService(android.content.Context.LOCATION_SERVICE) as LocationManager).removeUpdates(gpsListener) }+ MapGps.unsubscribe(mapGpsListener)listening = false}- private fun adaptGpsRate(fix: Location) {- val now = android.os.SystemClock.elapsedRealtime()- val moving = fix.hasSpeed() && fix.speed >= 1.0f- if (moving) stillSince = 0L else if (stillSince == 0L) stillSince = now- val parked = !moving && stillSince != 0L && now - stillSince > 60_000L- if (parked == gpsParked) return- gpsParked = parked- // Re-register with the new rate; the arrow stays where it is meanwhile.- if (listening) { stopGps(); startGps() }- }-// ---- North up / heading up / 3D --------------------------------------------------------------------private fun is3d() = tripId == null && Prefs.map3d(act) && Prefs.mapHeadingUp(act)@@ -1119,8 +1106,8 @@ class MapFragment : Fragment() {else Toast.makeText(act, "Waiting for a GPS fix...", Toast.LENGTH_SHORT).show()}- /** The best position known before this screen's own GPS answers: the running scan's fix, else the system's last known. */- private fun knownFix(): Location? = listOfNotNull(ScanForegroundService.lastFix, systemLastKnown()).maxByOrNull { it.time }+ /** The best position known before this screen's own GPS answers: the freshest precise fix from any source (see [MapGps.best]). */+ private fun knownFix(): Location? = MapGps.best(listOf(ScanForegroundService.lastFix, com.rfsentinel.app.nav.Navigator.lastFix, systemLastKnown()))@SuppressLint("MissingPermission")private fun systemLastKnown(): Location? {diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapGps.kt b/app/src/main/java/com/rfsentinel/app/ui/MapGps.ktnew file mode 100644index 0000000..ee20287--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/ui/MapGps.kt@@ -0,0 +1,133 @@+package com.rfsentinel.app.ui++import android.annotation.SuppressLint+import android.content.Context+import android.location.Location+import android.location.LocationManager+import android.os.Build+import android.os.Handler+import android.os.Looper+import androidx.core.location.LocationListenerCompat+import com.rfsentinel.app.util.Permissions+import java.util.concurrent.CopyOnWriteArrayList++/**+ * The position arrow's GPS, one for the whole app: the small map on the main screen and the full screen map share+ * it, so going from one to the other never restarts it - the arrow is where it was, at once. It keeps running a+ * little after the last map goes ([LINGER_MS]: a rotation, a quick look at another screen), then stops. A fix a+ * second (2 m) while moving, every 5 s (10 m) after a minute parked.+ *+ * [best] is the position to start a map with: the freshest fix from any source that is precise enough, so a coarse+ * WiFi / cell position (often 100 m off, across the road or a block away) does not stand in for a GPS one.+ */+object MapGps {+ const val LINGER_MS = 20_000L+ private const val MOVING_MS = 1_000L+ private const val PARKED_MS = 5_000L+ private const val PARK_AFTER_MS = 60_000L++ private val main = Handler(Looper.getMainLooper())+ private val subscribers = CopyOnWriteArrayList<(Location) -> Unit>()+ private var app: Context? = null+ private var listening = false+ private var parked = false+ private var stillSince = 0L+ private val stopLater = Runnable { stop() }++ // ---- the freshest good position, whoever got it -------------------------------------------------++ /** Recent fixes from every source (this GPS, guidance, the scan), newest last. */+ private val recent = ArrayDeque<Location>()++ /** Any fix the app gets (main thread or not): kept for [best]. */+ @Synchronized fun offer(fix: Location) {+ recent.addLast(Location(fix))+ while (recent.size > 8) recent.removeFirst()+ }++ /** The position to show before a fresh fix: the newest precise one (within [PRECISE_M]) not much older than the newest of all. */+ @Synchronized fun best(extra: List<Location?> = emptyList(), now: Long = System.currentTimeMillis()): Location? =+ pick(recent.toList() + extra.filterNotNull(), now)++ /** A fix this precise is a GPS one; a coarser one (WiFi, cell) is only used when there is nothing better. */+ const val PRECISE_M = 30f+ /** A precise fix may be this much older than a coarse one and still be preferred. */+ private const val PREFER_PRECISE_MS = 60_000L++ internal fun pick(all: List<Location>, now: Long): Location? {+ if (all.isEmpty()) return null+ val newest = all.maxBy { it.time }+ val precise = all.filter { it.hasAccuracy() && it.accuracy <= PRECISE_M }.maxByOrNull { it.time }+ return if (precise != null && newest.time - precise.time <= PREFER_PRECISE_MS) precise else newest+ }++ @Synchronized internal fun clearForTest() { recent.clear() }++ // ---- the shared GPS --------------------------------------------------------------------------++ private val listener = LocationListenerCompat { fix ->+ offer(fix)+ adapt(fix)+ subscribers.forEach { runCatching { it(fix) } }+ }++ /** Starts (or keeps) the GPS for [onFix]; the fix already known is handed over at once. Main thread. */+ fun subscribe(context: Context, onFix: (Location) -> Unit) {+ app = context.applicationContext+ main.removeCallbacks(stopLater)+ if (onFix !in subscribers) subscribers.add(onFix)+ start()+ }++ /** [onFix] no longer wants fixes; the GPS stops [LINGER_MS] after the last one goes. */+ fun unsubscribe(onFix: (Location) -> Unit) {+ subscribers.remove(onFix)+ if (subscribers.isEmpty()) { main.removeCallbacks(stopLater); main.postDelayed(stopLater, LINGER_MS) }+ }++ val running: Boolean get() = listening++ @SuppressLint("MissingPermission")+ private fun start() {+ val ctx = app ?: return+ if (listening || !Permissions.granted(ctx, android.Manifest.permission.ACCESS_FINE_LOCATION)) return+ val lm = ctx.getSystemService(Context.LOCATION_SERVICE) as LocationManager+ val provider = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && lm.hasProvider(LocationManager.FUSED_PROVIDER))+ LocationManager.FUSED_PROVIDER else LocationManager.GPS_PROVIDER+ val ms = if (parked) PARKED_MS else MOVING_MS+ val meters = if (parked) 10f else 2f+ runCatching {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+ val req = android.location.LocationRequest.Builder(ms)+ .setQuality(android.location.LocationRequest.QUALITY_HIGH_ACCURACY)+ .setMinUpdateDistanceMeters(meters)+ .build()+ lm.requestLocationUpdates(provider, req, ctx.mainExecutor, listener)+ } else lm.requestLocationUpdates(provider, ms, meters, listener, Looper.getMainLooper())+ listening = true+ }+ }++ private fun stop() {+ if (!listening || subscribers.isNotEmpty()) return+ val ctx = app ?: return+ runCatching { (ctx.getSystemService(Context.LOCATION_SERVICE) as LocationManager).removeUpdates(listener) }+ listening = false+ }++ /** Slower once parked for a minute, back to a fix a second when moving (re-registered; the arrow stays put meanwhile). */+ private fun adapt(fix: Location) {+ val now = android.os.SystemClock.elapsedRealtime()+ val moving = fix.hasSpeed() && fix.speed >= 1.0f+ if (moving) stillSince = 0L else if (stillSince == 0L) stillSince = now+ val p = !moving && stillSince != 0L && now - stillSince > PARK_AFTER_MS+ if (p == parked) return+ parked = p+ if (listening) {+ val ctx = app ?: return+ runCatching { (ctx.getSystemService(Context.LOCATION_SERVICE) as LocationManager).removeUpdates(listener) }+ listening = false+ start()+ }+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.ktindex a7f6278..fb1e5fd 100644--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt@@ -351,6 +351,9 @@ object Prefs {fun setNavAvoidSpeedCameras(context: Context, v: Boolean) = setBool(context, "nav_avoid_speed_cameras", v)fun navAvoidPlateReaders(context: Context): Boolean = bool(context, "nav_avoid_plate_readers", false)fun setNavAvoidPlateReaders(context: Context, v: Boolean) = setBool(context, "nav_avoid_plate_readers", v)+ /** Units for device distance estimates: "auto" (feet where the phone's region uses miles), "m" or "ft". */+ fun deviceUnits(context: Context): String = sp(context).getString("device_units", "auto") ?: "auto"+ fun setDeviceUnits(context: Context, v: String) = sp(context).edit { putString("device_units", v) }/** Distance units for guidance: "auto" (miles where the phone's region uses them), "km" or "mi". */fun navUnits(context: Context): String = sp(context).getString("nav_units", "auto") ?: "auto"fun setNavUnits(context: Context, v: String) = sp(context).edit { putString("nav_units", v) }diff --git a/app/src/test/java/com/rfsentinel/app/detect/DeviceDistanceUnitsTest.kt b/app/src/test/java/com/rfsentinel/app/detect/DeviceDistanceUnitsTest.ktnew file mode 100644index 0000000..abbcb89--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/detect/DeviceDistanceUnitsTest.kt@@ -0,0 +1,43 @@+package com.rfsentinel.app.detect++import android.app.Application+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.rfsentinel.app.util.Prefs+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.util.Locale++/** Device distance estimates in metres or in feet and miles (Settings > General > Device distances). */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35], application = Application::class)+class DeviceDistanceUnitsTest {+ private val ctx: Context = ApplicationProvider.getApplicationContext()++ @After fun reset() { Prefs.setDeviceUnits(ctx, "auto"); DeviceIntel.imperial = false }++ @Test+ fun feetAndMiles() {+ assertEquals("< 3 ft", DeviceIntel.formatDistance(0.5, true))+ assertEquals("~16 ft", DeviceIntel.formatDistance(5.0, true))+ assertEquals("~160 ft", DeviceIntel.formatDistance(50.0, true))+ assertEquals("~980 ft", DeviceIntel.formatDistance(300.0, true)); assertEquals("~0.2 mi", DeviceIntel.formatDistance(400.0, true))+ assertEquals("~50 m", DeviceIntel.formatDistance(50.0, false))+ }++ @Test+ fun theSettingDecidesAndAutomaticFollowsTheRegion() {+ Prefs.setDeviceUnits(ctx, "ft"); DeviceIntel.applyUnits(ctx, Locale.FRANCE); assertTrue(DeviceIntel.imperial)+ assertEquals("~30 ft", DeviceIntel.formatDistance(10.0))+ Prefs.setDeviceUnits(ctx, "m"); DeviceIntel.applyUnits(ctx, Locale.US); assertFalse(DeviceIntel.imperial)+ Prefs.setDeviceUnits(ctx, "auto")+ DeviceIntel.applyUnits(ctx, Locale.US); assertTrue(DeviceIntel.imperial)+ DeviceIntel.applyUnits(ctx, Locale.GERMANY); assertFalse(DeviceIntel.imperial)+ }+}diff --git a/app/src/test/java/com/rfsentinel/app/nav/RouteSnapTest.kt b/app/src/test/java/com/rfsentinel/app/nav/RouteSnapTest.ktnew file mode 100644index 0000000..183d431--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/nav/RouteSnapTest.kt@@ -0,0 +1,70 @@+package com.rfsentinel.app.nav++import android.app.Application+import android.location.Location+import com.rfsentinel.app.service.DeviceRegistry+import com.rfsentinel.app.ui.MapGps+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertSame+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** The arrow on the route while guided, and the position a map starts with. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35], application = Application::class)+class RouteSnapTest {+ private val lat0 = 45.0; private val lon0 = 7.0+ private fun lat(y: Double) = lat0 + y / 110_540.0+ private fun lon(x: Double) = lon0 + x / (111_320.0 * Math.cos(Math.toRadians(lat0)))++ /** 2 km due north. */+ private fun northRoad(): Route {+ val ys = (0..20).map { it * 100.0 }+ val lats = ys.map { lat(it) }.toDoubleArray(); val lons = DoubleArray(ys.size) { lon0 }+ val along = DoubleArray(ys.size)+ for (i in 1 until ys.size) along[i] = along[i - 1] + DeviceRegistry.metersBetween(lats[i - 1], lons[i - 1], lats[i], lons[i])+ return Route(lats, lons, along, along.last(), 120.0, emptyList(), "", lats.last() to lons.last())+ }++ @Test+ fun aFixAcrossTheRoadIsDrawnOnTheRouteFacingAlongIt() {+ // 12 m east of the road (the other side of it), heading a little off.+ val s = RouteSnap.snap(northRoad(), lat(500.0), lon(12.0), 20.0, 10.0, null)+ assertNotNull(s)+ assertEquals(lon0, s!!.lon, 1e-7)+ assertEquals(lat(500.0), s.lat, 2e-6)+ assertTrue("faces north: ${s.bearingDeg}", s.bearingDeg < 1.0 || s.bearingDeg > 359.0)+ }++ @Test+ fun aFixWellOffTheRouteIsLeftWhereItIs() {+ assertNull(RouteSnap.snap(northRoad(), lat(500.0), lon(60.0), 0.0, 5.0, null))+ // A rough fix allows a little more room, never past 40 m.+ assertNotNull(RouteSnap.snap(northRoad(), lat(500.0), lon(35.0), 0.0, 30.0, null))+ assertNull(RouteSnap.snap(northRoad(), lat(500.0), lon(45.0), 0.0, 100.0, null))+ }++ @Test+ fun goingAgainstTheRouteIsNotOnIt() {+ assertNull(RouteSnap.snap(northRoad(), lat(500.0), lon(8.0), 180.0, 5.0, null))+ // Stopped (no heading): put on it.+ assertNotNull(RouteSnap.snap(northRoad(), lat(500.0), lon(8.0), null, 5.0, null))+ }++ private fun fix(t: Long, acc: Float) = Location("t").apply { time = t; accuracy = acc; latitude = 1.0; longitude = 2.0 }++ @Test+ fun aMapStartsWithAPreciseFixRatherThanANewerCoarseOne() {+ val gps = fix(100_000, 8f); val cell = fix(130_000, 120f)+ assertSame(gps, MapGps.pick(listOf(gps, cell), 140_000))+ // A precise fix too old to trust: the newest one, coarse or not.+ val oldGps = fix(10_000, 8f)+ assertSame(cell, MapGps.pick(listOf(oldGps, cell), 140_000))+ assertNull(MapGps.pick(emptyList(), 0))+ }+}