Skip to content

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.

Share app UI, settings and detection helpers

greyxp1a1583fab9312
diff --git a/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt b/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt
index 328b026..8b6dc61 100644
--- a/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/CarMapRenderer.kt
@@ -3,6 +3,7 @@ package com.rfsentinel.app.car
import android.app.Presentation
import android.graphics.Rect
import android.graphics.drawable.BitmapDrawable
+import android.graphics.drawable.Drawable
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.os.Handler
@@ -159,15 +160,6 @@ class CarMapRenderer(private val carContext: CarContext, private val scope: Coro
fun recenter() { setFollowing(true); centreOnCar(); redraw() }
- /** Frames a whole route (e.g. when navigation starts); stops following. */
- fun showWholeRoute() {
- val m = map ?: return
- val pts = route?.actualPoints ?: return
- if (pts.size < 2) return
- setFollowing(false)
- m.zoomToBoundingBox(org.osmdroid.util.BoundingBox.fromGeoPoints(pts).increaseByScale(1.3f), false)
- }
-
private fun setFollowing(on: Boolean) {
if (following != on) { following = on; onFollowingChanged?.invoke() }
}
@@ -196,20 +188,10 @@ class CarMapRenderer(private val carContext: CarContext, private val scope: Coro
syncRoute(m)
me.items.clear()
com.rfsentinel.app.nav.Navigator.destination?.let { d ->
- me.add(Marker(m).apply {
- position = GeoPoint(d.lat, d.lon)
- icon = MapIcons.dot(dp, 0xFFD93025.toInt(), 20, 3f)
- setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
- setInfoWindow(null)
- })
+ me.add(marker(m, d.lat, d.lon, MapIcons.dot(dp, 0xFFD93025.toInt(), 20, 3f)))
}
CarUi.currentLocation(carContext)?.let { fix ->
- me.add(Marker(m).apply {
- position = GeoPoint(fix.latitude, fix.longitude)
- icon = MapIcons.dot(dp, 0xFF1A73E8.toInt(), 22, 3f)
- setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
- setInfoWindow(null)
- })
+ me.add(marker(m, fix.latitude, fix.longitude, MapIcons.dot(dp, 0xFF1A73E8.toInt(), 22, 3f)))
}
// Devices: ordinary first so flagged ones are drawn on top.
@@ -231,12 +213,8 @@ class CarMapRenderer(private val carContext: CarContext, private val scope: Coro
devicesKey = placed
devices.items.clear()
for (d in placed) {
- devices.add(Marker(m).apply {
- position = GeoPoint(d.lat, d.lon)
- icon = dotIcons.getOrPut((d.color.toLong() shl 8) or d.sizeDp.toLong()) { MapIcons.dot(dp, d.color, d.sizeDp) }
- setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
- setInfoWindow(null)
- })
+ val icon = dotIcons.getOrPut((d.color.toLong() shl 8) or d.sizeDp.toLong()) { MapIcons.dot(dp, d.color, d.sizeDp) }
+ devices.add(marker(m, d.lat, d.lon, icon))
}
}
@@ -249,12 +227,7 @@ class CarMapRenderer(private val carContext: CarContext, private val scope: Coro
if (showTowers) com.rfsentinel.app.service.CellTowerStore.all(carContext).forEach { t ->
val lat = t.bestLat ?: return@forEach
val lon = t.bestLon ?: return@forEach
- towers.add(Marker(m).apply {
- position = GeoPoint(lat, lon)
- icon = towerIcon
- setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
- setInfoWindow(null)
- })
+ towers.add(marker(m, lat, lon, towerIcon))
}
}
@@ -271,13 +244,8 @@ class CarMapRenderer(private val carContext: CarContext, private val scope: Coro
camerasKey = cKey
cameras.items.clear()
inBox.forEach { c ->
- cameras.add(Marker(m).apply {
- position = GeoPoint(c.lat, c.lon)
- // Silenced cameras stay on the map, faded (like on the phone).
- icon = (if (c.osmId in ignoredIds) fadedCameraIcons else cameraIcons)[c.type]
- setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
- setInfoWindow(null)
- })
+ // Silenced cameras stay on the map, faded (like on the phone).
+ cameras.add(marker(m, c.lat, c.lon, (if (c.osmId in ignoredIds) fadedCameraIcons else cameraIcons)[c.type]))
}
}
// Fetch the cameras for wherever the driver moved the map.
@@ -293,6 +261,13 @@ class CarMapRenderer(private val carContext: CarContext, private val scope: Coro
m.invalidate()
}
+ private fun marker(map: MapView, lat: Double, lon: Double, drawable: Drawable?): Marker = Marker(map).apply {
+ position = GeoPoint(lat, lon)
+ icon = drawable
+ setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
+ setInfoWindow(null)
+ }
+
private data class DeviceDot(val lat: Double, val lon: Double, val color: Int, val sizeDp: Int)
private var drawnRoute: com.rfsentinel.app.nav.Route? = null
diff --git a/app/src/main/java/com/rfsentinel/app/car/CellsScreen.kt b/app/src/main/java/com/rfsentinel/app/car/CellsScreen.kt
index fb38d75..d162069 100644
--- a/app/src/main/java/com/rfsentinel/app/car/CellsScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/CellsScreen.kt
@@ -1,10 +1,7 @@
package com.rfsentinel.app.car
import androidx.car.app.CarContext
-import androidx.car.app.model.Action
import androidx.car.app.model.CarColor
-import androidx.car.app.model.ItemList
-import androidx.car.app.model.ListTemplate
import androidx.car.app.model.Row
import androidx.car.app.model.Template
import com.rfsentinel.app.R
@@ -27,65 +24,33 @@ class CellsScreen(carContext: CarContext) : LiveScreen(carContext, periodMs = 5_
Prefs.categoryEnabled(carContext, Category.CELL_ANOMALY)
)
- @Suppress("DEPRECATION") // setTitle keeps compatibility with older Android Auto hosts
override fun render(): Template {
- val items = ItemList.Builder()
val running = ScanForegroundService.isRunning
val checks = Prefs.categoryEnabled(carContext, Category.CELL_ANOMALY)
-
- // 1. Fake-cell check status.
val warning = recentWarning()
- items.addItem(
- when {
- warning != null -> Row.Builder()
- .setTitle(warning.second.title)
- .addText(CarUi.ageText(System.currentTimeMillis() - warning.first) + " · " + warning.second.detail.take(90))
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_warning, CarUi.DANGER_COLOR))
- .build()
- !checks -> Row.Builder()
- .setTitle("Fake cell tower checks are off")
- .addText("Turn on the category in Settings on your phone")
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_tower))
- .build()
- !running -> Row.Builder()
- .setTitle("Not scanning")
- .addText("Cells are checked every 15 s while scanning")
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_tower))
- .build()
- else -> Row.Builder()
- .setTitle("No fake-cell signs")
- .addText("Checked every 15 s - a hint, not proof")
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_tower, CarUi.CLEAR_COLOR))
- .build()
- }
- )
-
- // 2. The serving cell, then the strongest neighbours.
+ val status = when {
+ warning != null -> row(warning.second.title,
+ CarUi.ageText(System.currentTimeMillis() - warning.first) + " · " + warning.second.detail.take(90),
+ icon = R.drawable.ic_car_warning, color = CarUi.DANGER_COLOR)
+ !checks -> row("Fake cell tower checks are off", "Turn on the category in Settings on your phone", icon = R.drawable.ic_car_tower)
+ !running -> row("Not scanning", "Cells are checked every 15 s while scanning", icon = R.drawable.ic_car_tower)
+ else -> row("No fake-cell signs", "Checked every 15 s - a hint, not proof", icon = R.drawable.ic_car_tower, color = CarUi.CLEAR_COLOR)
+ }
val cells = if (running) CellTowerStore.current else emptyList()
- cells.sortedWith(compareByDescending<CellAnalyzer.Cell> { it.registered }.thenByDescending { it.dbm ?: -999 })
- .take((CarUi.listLimit(carContext) - 1).coerceAtLeast(0))
- .forEach { c -> items.addItem(cellRow(c)) }
-
- return ListTemplate.Builder()
- .setTitle("Cell towers")
- .setHeaderAction(Action.BACK)
- .setSingleList(items.build())
- .build()
+ val neighbours = cells.sortedWith(compareByDescending<CellAnalyzer.Cell> { it.registered }.thenByDescending { it.dbm ?: -999 })
+ .take((CarUi.listLimit(carContext) - 1).coerceAtLeast(0)).map { cellRow(it) }
+ return listTemplate("Cell towers", listOf(status) + neighbours)
}
- private fun cellRow(c: CellAnalyzer.Cell): Row {
- val row = Row.Builder()
- .setTitle(c.rat.label + if (c.registered) " · serving" else " · neighbour")
- .addText(listOfNotNull(
- c.operator,
- if (c.mcc != null || c.mnc != null) "${c.mcc ?: "?"}-${c.mnc ?: "?"}" else null,
- c.cellId?.let { "cell $it" } ?: c.pci?.let { "PCI $it" },
- c.dbm?.let { "$it dBm" }
- ).joinToString(" · ").ifEmpty { "No IDs reported" })
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_tower, if (c.registered) CarUi.CLEAR_COLOR else null))
- // A tower with an estimated spot (where its signal was strongest) opens on the map.
- if (c.cellId != null) {
- row.setOnClickListener {
+ private fun cellRow(c: CellAnalyzer.Cell): Row = row(
+ c.rat.label + if (c.registered) " · serving" else " · neighbour",
+ listOfNotNull(c.operator,
+ if (c.mcc != null || c.mnc != null) "${c.mcc ?: "?"}-${c.mnc ?: "?"}" else null,
+ c.cellId?.let { "cell $it" } ?: c.pci?.let { "PCI $it" }, c.dbm?.let { "$it dBm" }
+ ).joinToString(" · ").ifEmpty { "No IDs reported" },
+ icon = R.drawable.ic_car_tower, color = if (c.registered) CarUi.CLEAR_COLOR else null,
+ onClick = if (c.cellId == null) null else {
+ {
val t = CellTowerStore.all(carContext).firstOrNull { it.key == c.key }
val lat = t?.bestLat
val lon = t?.bestLon
@@ -98,8 +63,7 @@ class CellsScreen(carContext: CarContext) : LiveScreen(carContext, periodMs = 5_
}
}
}
- return row.build()
- }
+ )
private fun recentWarning() = CellMonitor.lastAnomaly?.takeIf { System.currentTimeMillis() - it.first < WARNING_MS }
diff --git a/app/src/main/java/com/rfsentinel/app/car/DestinationScreen.kt b/app/src/main/java/com/rfsentinel/app/car/DestinationScreen.kt
index 2bb0870..c6bd7a3 100644
--- a/app/src/main/java/com/rfsentinel/app/car/DestinationScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/DestinationScreen.kt
@@ -3,8 +3,6 @@ package com.rfsentinel.app.car
import androidx.car.app.CarContext
import androidx.car.app.CarToast
import androidx.car.app.model.Action
-import androidx.car.app.model.ItemList
-import androidx.car.app.model.Row
import androidx.car.app.model.SearchTemplate
import androidx.car.app.model.Template
import androidx.lifecycle.lifecycleScope
@@ -30,33 +28,25 @@ class DestinationScreen(carContext: CarContext, private val map: LiveMapScreen)
private var typed = ""
override fun buildTemplate(): Template {
- val list = ItemList.Builder()
+ val rows = ArrayList<androidx.car.app.model.Row>()
val shown = results ?: savedPlaces()
val me = CarUi.currentLocation(carContext)
// Some cars' keyboards don't send "submit": offer the search as a row too.
if (typed.isNotBlank() && typed != query) {
- list.addItem(Row.Builder()
- .setTitle("Search \"${typed.trim()}\"")
- .addText("in OpenStreetMap")
- .setOnClickListener { search(typed) }
- .build())
+ rows += row("Search \"${typed.trim()}\"", "in OpenStreetMap") { search(typed) }
}
// The car shows a few rows at a time (and the "Search" row above takes one): the best matches come first.
val room = CarUi.listLimit(carContext) - if (typed.isNotBlank() && typed != query) 1 else 0
shown.take(room.coerceAtLeast(1)).forEach { d ->
- val row = Row.Builder().setTitle(d.name)
// Short for a car screen (older saved entries may hold the full address).
val where = d.address.split(", ").filter { it.isNotBlank() }.take(2).joinToString(", ").ifBlank { "OpenStreetMap" }
- row.addText(
+ rows += row(d.name,
if (me != null) NearbyMapScreen.distanceText(DeviceRegistry.metersBetween(me.latitude, me.longitude, d.lat, d.lon)) + " · " + where
- else where
- )
- row.setOnClickListener { go(d) }
- list.addItem(row.build())
- }
- if (shown.isEmpty() && !loading && (typed.isBlank() || typed == query)) {
- list.setNoItemsMessage(if (results == null) "Search for an address or a place" else "Nothing found for \"$query\"")
+ else where) { go(d) }
}
+ val noItems = if (shown.isEmpty() && !loading && (typed.isBlank() || typed == query)) {
+ if (results == null) "Search for an address or a place" else "Nothing found for \"$query\""
+ } else null
return SearchTemplate.Builder(object : SearchTemplate.SearchCallback {
override fun onSearchSubmitted(searchText: String) = search(searchText)
override fun onSearchTextChanged(searchText: String) {
@@ -71,7 +61,7 @@ class DestinationScreen(carContext: CarContext, private val map: LiveMapScreen)
.setSearchHint("Destination (searched in OpenStreetMap)")
.setShowKeyboardByDefault(results == null && savedPlaces().isEmpty())
.setLoading(loading)
- .apply { if (!loading) setItemList(list.build()) }
+ .apply { if (!loading) setItemList(itemList(rows, noItems)) }
.build()
}
diff --git a/app/src/main/java/com/rfsentinel/app/car/DeviceDetailScreen.kt b/app/src/main/java/com/rfsentinel/app/car/DeviceDetailScreen.kt
index 7a29f0d..8fd8cf8 100644
--- a/app/src/main/java/com/rfsentinel/app/car/DeviceDetailScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/DeviceDetailScreen.kt
@@ -26,7 +26,6 @@ import com.rfsentinel.app.oui.OuiWatchlist
import com.rfsentinel.app.service.DeviceRegistry
import com.rfsentinel.app.util.ProximityUtil
import kotlinx.coroutines.launch
-import java.util.Locale
/**
* One device on the car screen: why it's flagged, live signal, which radio heard
@@ -51,34 +50,18 @@ class DeviceDetailScreen(carContext: CarContext, private val mac: String) : Live
val best = s.best
val rows = mutableListOf<Row>()
- rows += Row.Builder()
- .setTitle(CarUi.title(s))
- .addText(CarUi.tagLine(s))
- .setImage(CarUi.icon(carContext, if (CarUi.isFlagged(s)) R.drawable.ic_car_warning else R.drawable.ic_tile_scan, CarUi.colorFor(s)))
- .build()
- if (best != null) {
- rows += Row.Builder().setTitle("Why").addText(best.evidence.take(120)).build()
- }
- rows += Row.Builder()
- .setTitle("Signal ${s.rssi} dBm · ${ProximityUtil.band(s.rssi)}${trend(s)}")
- .addText("${DeviceIntel.formatDistance(s.distanceM)} (rough) · best ${s.bestRssi} dBm")
- .build()
+ rows += row(CarUi.title(s), CarUi.tagLine(s),
+ icon = if (CarUi.isFlagged(s)) R.drawable.ic_car_warning else R.drawable.ic_tile_scan, color = CarUi.colorFor(s))
+ if (best != null) rows += row("Why", best.evidence.take(120))
+ rows += row("Signal ${s.rssi} dBm · ${ProximityUtil.band(s.rssi)}${trend(s)}",
+ "${DeviceIntel.formatDistance(s.distanceM)} (rough) · best ${s.bestRssi} dBm")
s.remoteId?.takeIf { it.hasPosition }?.let { r ->
- rows += Row.Builder()
- .setTitle("Drone " + (r.uasId ?: ""))
- .addText(
- listOfNotNull(
- r.heightM?.let { com.rfsentinel.app.util.Units.length(it) + " high" },
- r.speedMs?.let { com.rfsentinel.app.util.Units.speed(it) },
- r.status
- ).joinToString(" · ").ifEmpty { "Position known" }
- )
- .build()
+ rows += row("Drone " + (r.uasId ?: ""), listOfNotNull(
+ r.heightM?.let { com.rfsentinel.app.util.Units.length(it) + " high" },
+ r.speedMs?.let { com.rfsentinel.app.util.Units.speed(it) }, r.status
+ ).joinToString(" · ").ifEmpty { "Position known" })
}
- rows += Row.Builder()
- .setTitle(s.vendor ?: s.deviceType)
- .addText("$mac · ${s.addressType.label} · heard by ${heardBy(s)}")
- .build()
+ rows += row(s.vendor ?: s.deviceType, "$mac · ${s.addressType.label} · heard by ${heardBy(s)}")
val pane = Pane.Builder()
rows.take(CarUi.paneLimit(carContext)).forEach { pane.addRow(it) }
@@ -87,20 +70,14 @@ class DeviceDetailScreen(carContext: CarContext, private val mac: String) : Live
val whitelisted = WhitelistCache.inTable(mac)
val ignored = TrackerMutes.isMuted(mac)
val tracker = best?.category == Category.TRACKER && s.addressType != AddressType.PUBLIC
- pane.addAction(
- Action.Builder()
- .setTitle(when { ignored -> "Stop ignoring"; whitelisted -> "Un-whitelist"; tracker -> "Ignore..."; else -> "Whitelist" })
- .setOnClickListener {
- when {
- ignored -> { TrackerMutes.unmute(carContext, mac); toast("No longer ignored") }
- // Its address changes daily, so it can't be whitelisted: offer the phone's choices.
- tracker && !whitelisted -> screenManager.push(TrackerIgnoreScreen(carContext, mac))
- else -> toggleWhitelist(whitelisted, best?.label ?: s.name ?: "")
- }
- invalidate()
- }
- .build()
- )
+ pane.addAction(action(when { ignored -> "Stop ignoring"; whitelisted -> "Un-whitelist"; tracker -> "Ignore..."; else -> "Whitelist" }) {
+ when {
+ ignored -> { TrackerMutes.unmute(carContext, mac); toast("No longer ignored") }
+ tracker && !whitelisted -> screenManager.push(TrackerIgnoreScreen(carContext, mac))
+ else -> toggleWhitelist(whitelisted, best?.label ?: s.name ?: "")
+ }
+ invalidate()
+ })
val watched = OuiWatchlist.customEntry(mac) != null
pane.addAction(
Action.Builder()
@@ -113,29 +90,18 @@ class DeviceDetailScreen(carContext: CarContext, private val mac: String) : Live
// Action strip: favorite, and navigate to a drone's broadcast position.
val strip = ActionStrip.Builder()
val fav = Favorites.contains(mac)
- strip.addAction(
- Action.Builder()
- .setIcon(CarUi.icon(carContext, if (fav) R.drawable.ic_car_star else R.drawable.ic_car_star_outline))
- .setOnClickListener {
- lifecycleScope.launch {
- Favorites.set(carContext, mac, !fav, s.name, s.vendor, s.deviceType)
- toast(if (fav) "Removed from favorites" else "Added to favorites")
- invalidate()
- }
- }
- .build()
- )
+ strip.addAction(action(icon = if (fav) R.drawable.ic_car_star else R.drawable.ic_car_star_outline) {
+ lifecycleScope.launch {
+ Favorites.set(carContext, mac, !fav, s.name, s.vendor, s.deviceType)
+ toast(if (fav) "Removed from favorites" else "Added to favorites")
+ invalidate()
+ }
+ })
s.remoteId?.let { r ->
val lat = r.latitude ?: r.operatorLatitude
val lon = r.longitude ?: r.operatorLongitude
if (lat != null && lon != null) {
- strip.addAction(
- Action.Builder()
- .setTitle("Navigate")
- .setIcon(CarUi.icon(carContext, R.drawable.ic_car_navigate))
- .setOnClickListener { CarUi.navigateTo(carContext, lat, lon) }
- .build()
- )
+ strip.addAction(action("Navigate", R.drawable.ic_car_navigate) { CarUi.navigateTo(carContext, lat, lon) })
}
}
@@ -159,29 +125,19 @@ class DeviceDetailScreen(carContext: CarContext, private val mac: String) : Live
else e.categoryEnum?.colorArgb ?: CarUi.DANGER_COLOR
val pane = Pane.Builder()
listOf(
- Row.Builder().setTitle((if (e.following) "FOLLOWING · " else "") + e.label)
- .addText("Out of range · last alert ${CarUi.ageText(now - e.time)}" + (e.rssi?.let { " · $it dBm" } ?: ""))
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_warning, color)).build(),
- Row.Builder().setTitle("Why").addText(e.evidence.take(120)).build(),
- Row.Builder().setTitle(mac).addText("${e.categoryEnum?.title ?: e.category} · ${e.confidence}%").build()
+ row((if (e.following) "FOLLOWING · " else "") + e.label,
+ "Out of range · last alert ${CarUi.ageText(now - e.time)}" + (e.rssi?.let { " · $it dBm" } ?: ""),
+ icon = R.drawable.ic_car_warning, color = color),
+ row("Why", e.evidence.take(120)),
+ row(mac, "${e.categoryEnum?.title ?: e.category} · ${e.confidence}%")
).take(CarUi.paneLimit(carContext)).forEach { pane.addRow(it) }
val whitelisted = WhitelistCache.inTable(mac)
- pane.addAction(
- Action.Builder()
- .setTitle(if (whitelisted) "Un-whitelist" else "Whitelist")
- .setOnClickListener { toggleWhitelist(whitelisted, e.label) }
- .build()
- )
+ pane.addAction(action(if (whitelisted) "Un-whitelist" else "Whitelist") { toggleWhitelist(whitelisted, e.label) })
val lat = e.lat
val lon = e.lon
if (lat != null && lon != null) {
- pane.addAction(
- Action.Builder()
- .setTitle("Navigate there")
- .setOnClickListener { CarUi.navigateTo(carContext, lat, lon) }
- .build()
- )
+ pane.addAction(action("Navigate there") { CarUi.navigateTo(carContext, lat, lon) })
}
return PaneTemplate.Builder(pane.build())
.setTitle("Device details")
diff --git a/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt b/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt
index 282b803..875098a 100644
--- a/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/DeviceListScreen.kt
@@ -1,10 +1,6 @@
package com.rfsentinel.app.car
import androidx.car.app.CarContext
-import androidx.car.app.model.Action
-import androidx.car.app.model.ItemList
-import androidx.car.app.model.ListTemplate
-import androidx.car.app.model.Row
import androidx.car.app.model.Template
import com.rfsentinel.app.R
import com.rfsentinel.app.service.DeviceRegistry
@@ -28,37 +24,14 @@ class DeviceListScreen(carContext: CarContext, private val filter: DeviceFilter)
return listOf(ScanForegroundService.isRunning) + matching(now).map { CarUi.rowKey(it, now) }
}
- @Suppress("DEPRECATION") // setTitle keeps compatibility with older Android Auto hosts
override fun render(): Template {
val now = System.currentTimeMillis()
- val items = ItemList.Builder()
- // The car caps list length while driving; the most important come first.
- matching(now).forEach { s ->
- items.addItem(
- Row.Builder()
- .setTitle(CarUi.title(s))
- .addText(CarUi.tagLine(s))
- .addText(CarUi.signalLine(s, now))
- .setImage(
- CarUi.icon(
- carContext,
- if (CarUi.isFlagged(s)) R.drawable.ic_car_warning else R.drawable.ic_tile_scan,
- CarUi.colorFor(s)
- )
- )
- .setOnClickListener { screenManager.push(DeviceDetailScreen(carContext, s.mac)) }
- .build()
- )
- }
- items.setNoItemsMessage(emptyMessage(filter))
-
- // Title stays constant: Android Auto only treats a same-title template as a
- // refresh rather than a new step (steps are capped for driver safety).
- return ListTemplate.Builder()
- .setTitle(titleOf(filter))
- .setHeaderAction(Action.BACK)
- .setSingleList(items.build())
- .build()
+ // The title stays constant so Android Auto treats updates as refreshes.
+ return listTemplate(titleOf(filter), matching(now).map { s ->
+ row(CarUi.title(s), CarUi.tagLine(s), CarUi.signalLine(s, now),
+ icon = if (CarUi.isFlagged(s)) R.drawable.ic_car_warning else R.drawable.ic_tile_scan,
+ color = CarUi.colorFor(s)) { screenManager.push(DeviceDetailScreen(carContext, s.mac)) }
+ }, emptyMessage(filter))
}
companion object {
diff --git a/app/src/main/java/com/rfsentinel/app/car/DevicesMapScreen.kt b/app/src/main/java/com/rfsentinel/app/car/DevicesMapScreen.kt
index acbc1e6..1e7861b 100644
--- a/app/src/main/java/com/rfsentinel/app/car/DevicesMapScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/DevicesMapScreen.kt
@@ -1,19 +1,7 @@
package com.rfsentinel.app.car
-import android.text.SpannableString
-import android.text.Spanned
import androidx.car.app.CarContext
-import androidx.car.app.model.Action
-import androidx.car.app.model.ActionStrip
import androidx.car.app.model.CarColor
-import androidx.car.app.model.CarLocation
-import androidx.car.app.model.DistanceSpan
-import androidx.car.app.model.ItemList
-import androidx.car.app.model.Metadata
-import androidx.car.app.model.Place
-import androidx.car.app.model.PlaceListMapTemplate
-import androidx.car.app.model.PlaceMarker
-import androidx.car.app.model.Row
import androidx.car.app.model.Template
import com.rfsentinel.app.data.WhitelistCache
import com.rfsentinel.app.detect.Tier
@@ -49,45 +37,18 @@ class DevicesMapScreen(carContext: CarContext) : LiveScreen(carContext, periodMs
val limit = CarUi.listLimit(carContext).coerceAtMost(6)
val items = if (me == null) emptyList() else around(me.latitude, me.longitude, limit)
- val list = ItemList.Builder()
- if (items.isEmpty()) list.setNoItemsMessage(
- when {
- !ScanForegroundService.isRunning -> "Not scanning - tap Start on the RF Sentinel home screen"
- me == null -> "Waiting for your location..."
- else -> "No devices placed yet - they appear as GPS fixes come in"
+ val noItems = when {
+ !ScanForegroundService.isRunning -> "Not scanning - tap Start on the RF Sentinel home screen"
+ me == null -> "Waiting for your location..."
+ else -> "No devices placed yet - they appear as GPS fixes come in"
+ }
+ return mapTemplate("Devices around me", items.map { item ->
+ mapRow(item.title, item.detail, item.lat, item.lon, item.distanceM,
+ CarColor.createCustom(item.color, item.color), item.tag) {
+ screenManager.push(DeviceDetailScreen(carContext, item.mac))
}
- )
- items.forEach { list.addItem(row(it)) }
-
- val template = PlaceListMapTemplate.Builder()
- .setTitle("Devices around me")
- .setHeaderAction(Action.BACK)
- .setCurrentLocationEnabled(me != null)
- .setActionStrip(
- ActionStrip.Builder().addAction(
- Action.Builder().setTitle("Cameras")
- .setOnClickListener { screenManager.push(NearbyMapScreen(carContext, fromDevicesMap = true)) }
- .build()
- ).build()
- )
- .setItemList(list.build())
- if (me != null) template.setAnchor(Place.Builder(CarLocation.create(me.latitude, me.longitude)).build())
- return template.build()
- }
-
- private fun row(it: Item): Row {
- val marker = PlaceMarker.Builder().setColor(CarColor.createCustom(it.color, it.color))
- it.tag?.let { t -> marker.setLabel(t) } // W = WiFi, B = Bluetooth, else the category's first letter
- val place = Place.Builder(CarLocation.create(it.lat, it.lon)).setMarker(marker.build()).build()
- // Map rows must carry their distance as a DistanceSpan (the car formats it).
- val text = SpannableString(" · " + it.detail)
- text.setSpan(DistanceSpan.create(NearbyMapScreen.distanceOf(it.distanceM)), 0, 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
- return Row.Builder()
- .setTitle(it.title)
- .addText(text)
- .setMetadata(Metadata.Builder().setPlace(place).build())
- .setOnClickListener { screenManager.push(DeviceDetailScreen(carContext, it.mac)) }
- .build()
+ }, action("Cameras") { screenManager.push(NearbyMapScreen(carContext, fromDevicesMap = true)) },
+ location = me, noItems = noItems.takeIf { items.isEmpty() })
}
companion object {
diff --git a/app/src/main/java/com/rfsentinel/app/car/HardwareScreen.kt b/app/src/main/java/com/rfsentinel/app/car/HardwareScreen.kt
index 28e4d2c..9c0f7cc 100644
--- a/app/src/main/java/com/rfsentinel/app/car/HardwareScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/HardwareScreen.kt
@@ -1,10 +1,6 @@
package com.rfsentinel.app.car
import androidx.car.app.CarContext
-import androidx.car.app.model.Action
-import androidx.car.app.model.ItemList
-import androidx.car.app.model.ListTemplate
-import androidx.car.app.model.Row
import androidx.car.app.model.Template
import com.rfsentinel.app.R
import com.rfsentinel.app.esp.EspBoards
@@ -50,16 +46,8 @@ class HardwareScreen(carContext: CarContext) : LiveScreen(carContext, periodMs =
override fun contentKey(): Any = lines()
- @Suppress("DEPRECATION") // setTitle keeps compatibility with older Android Auto hosts
- override fun render(): Template {
- val items = ItemList.Builder()
- lines().take(CarUi.listLimit(carContext)).forEach { (title, text, icon) ->
- items.addItem(Row.Builder().setTitle(title).addText(text.take(120)).setImage(CarUi.icon(carContext, icon)).build())
- }
- return ListTemplate.Builder()
- .setTitle("Hardware")
- .setHeaderAction(Action.BACK)
- .setSingleList(items.build())
- .build()
- }
+ override fun render(): Template = listTemplate("Hardware",
+ lines().take(CarUi.listLimit(carContext)).map { (title, text, icon) ->
+ row(title, text.take(120), icon = icon)
+ })
}
diff --git a/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt b/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt
index 67c51d5..0a8090d 100644
--- a/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/HomeScreen.kt
@@ -4,8 +4,6 @@ import androidx.car.app.CarContext
import androidx.car.app.CarToast
import androidx.car.app.model.Action
import androidx.car.app.model.ActionStrip
-import androidx.car.app.model.ItemList
-import androidx.car.app.model.ListTemplate
import androidx.car.app.model.Row
import androidx.car.app.model.Template
import com.rfsentinel.app.R
@@ -71,124 +69,62 @@ class HomeScreen(carContext: CarContext) : LiveScreen(carContext) {
)
}
- @Suppress("DEPRECATION") // setTitle/setActionStrip keep compatibility with older Android Auto hosts
override fun render(): Template {
val m = model()
val now = System.currentTimeMillis()
val rows = ArrayList<Row>()
-
- // 1. Headline: the threat level; tap for the flagged devices.
rows += if (m.running) {
val (color, text) = m.headline!!
- Row.Builder()
- .setTitle(text)
- .addText(listOf("Scanning · ${m.devices} nearby · ${m.flagged} flagged", m.silenced,
- if (m.screenOff) SCREEN_OFF_SHORT else "")
- .filter { it.isNotEmpty() }.joinToString(" · "))
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_warning, color))
- .setBrowsable(true)
- .setOnClickListener { screenManager.push(DeviceListScreen(carContext, DeviceFilter.FLAGGED)) }
- .build()
+ row(text, listOf("Scanning · ${m.devices} nearby · ${m.flagged} flagged", m.silenced,
+ if (m.screenOff) SCREEN_OFF_SHORT else "").filter { it.isNotEmpty() }.joinToString(" · "),
+ icon = R.drawable.ic_car_warning, color = color, browsable = true) {
+ screenManager.push(DeviceListScreen(carContext, DeviceFilter.FLAGGED))
+ }
} else {
- Row.Builder()
- .setTitle("Not scanning")
- .addText("Tap Start to listen for nearby equipment")
- .setImage(CarUi.icon(carContext, R.drawable.ic_tile_scan))
- .build()
+ row("Not scanning", "Tap Start to listen for nearby equipment", icon = R.drawable.ic_tile_scan)
}
-
- // 2. The next known camera on your way (works without scanning too).
m.camera?.let { (cam, d) ->
- rows += Row.Builder()
- .setTitle("${cam.label} ahead")
- .addText(NearbyMapScreen.distanceText(d) + (cam.operator?.let { " · $it" } ?: ""))
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_warning, NearbyMapScreen.cameraColor(cam.type)))
- .setBrowsable(true)
- .setOnClickListener { screenManager.push(PlaceFocusScreen.forCamera(carContext, cam)) }
- .build()
- }
-
- // 3. Recent alerts (still there after the device has left).
- rows += Row.Builder()
- .setTitle("Recent alerts (${m.alerts})")
- .addText(m.newestAlert?.let { "${it.label} · ${CarUi.ageText(now - it.time)}" } ?: "None yet")
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_history))
- .setBrowsable(true)
- .setOnClickListener { screenManager.push(RecentAlertsScreen(carContext)) }
- .build()
-
- // 4. Map: our own pannable map when the car allows it, else the car-drawn one.
- rows += Row.Builder()
- .setTitle(if (m.liveMap) "Live map & navigation" else "Map: devices & cameras around me")
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_navigate))
- .setBrowsable(true)
- .setOnClickListener {
- screenManager.push(if (m.liveMap) LiveMapScreen(carContext) else DevicesMapScreen(carContext))
+ rows += row("${cam.label} ahead", NearbyMapScreen.distanceText(d) + (cam.operator?.let { " · $it" } ?: ""),
+ icon = R.drawable.ic_car_warning, color = NearbyMapScreen.cameraColor(cam.type), browsable = true) {
+ screenManager.push(PlaceFocusScreen.forCamera(carContext, cam))
}
- .build()
-
- // 5. Everything nearby, filtered like the phone's chips.
- rows += Row.Builder()
- .setTitle("Nearby devices (${m.devices})")
- .addText("Flagged, trackers, drones, favorites, new, external...")
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_drone))
- .setBrowsable(true)
- .setOnClickListener { screenManager.push(NearbyDevicesScreen(carContext)) }
- .build()
-
- // 6. Cell towers when there is room (no camera row), then More.
+ }
+ rows += row("Recent alerts (${m.alerts})",
+ m.newestAlert?.let { "${it.label} · ${CarUi.ageText(now - it.time)}" } ?: "None yet",
+ icon = R.drawable.ic_car_history, browsable = true) { screenManager.push(RecentAlertsScreen(carContext)) }
+ rows += row(if (m.liveMap) "Live map & navigation" else "Map: devices & cameras around me",
+ icon = R.drawable.ic_car_navigate, browsable = true) {
+ screenManager.push(if (m.liveMap) LiveMapScreen(carContext) else DevicesMapScreen(carContext))
+ }
+ rows += row("Nearby devices (${m.devices})", "Flagged, trackers, drones, favorites, new, external...",
+ icon = R.drawable.ic_car_drone, browsable = true) { screenManager.push(NearbyDevicesScreen(carContext)) }
if (m.camera == null && m.cellSummary != null) {
- rows += Row.Builder()
- .setTitle("Cell towers")
- .addText(m.cellSummary)
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_tower))
- .setBrowsable(true)
- .setOnClickListener { screenManager.push(CellsScreen(carContext)) }
- .build()
+ rows += row("Cell towers", m.cellSummary, icon = R.drawable.ic_car_tower, browsable = true) {
+ screenManager.push(CellsScreen(carContext))
+ }
}
- rows += Row.Builder()
- .setTitle("More")
- .addText("Snooze alerts, voice, cell towers, hardware")
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_more))
- .setBrowsable(true)
- .setOnClickListener { screenManager.push(MoreScreen(carContext)) }
- .build()
-
- // The car shows only its row limit while driving: More must stay reachable.
+ rows += row("More", "Snooze alerts, voice, cell towers, hardware", icon = R.drawable.ic_car_more, browsable = true) {
+ screenManager.push(MoreScreen(carContext))
+ }
+ // More must stay reachable even when the host limits the row count.
val limit = CarUi.listLimit(carContext)
val shown = if (rows.size <= limit) rows else rows.take(limit - 1) + rows.last()
- val items = ItemList.Builder()
- shown.forEach { items.addItem(it) }
-
- val running = m.running
- val startStop = Action.Builder()
- .setTitle(if (running) "Stop" else "Start")
- .setIcon(CarUi.icon(carContext, if (running) R.drawable.ic_car_stop else R.drawable.ic_car_play))
- .setOnClickListener { if (ScanForegroundService.isRunning) stop() else start() }
- .build()
-
- // Master mute: alert tone + voice (plays through the car speakers otherwise).
- // Icon-only: Android Auto allows a single titled button in this strip.
+ val startStop = action(if (m.running) "Stop" else "Start",
+ if (m.running) R.drawable.ic_car_stop else R.drawable.ic_car_play) {
+ if (ScanForegroundService.isRunning) stop() else start()
+ }
+ // Icon-only: Android Auto permits a single titled button in this strip.
val muted = Prefs.alertsMuted(carContext)
- val muteButton = Action.Builder()
- .setIcon(CarUi.icon(carContext, if (muted) R.drawable.ic_car_volume_off else R.drawable.ic_car_volume))
- .setOnClickListener {
- val nowMuted = !Prefs.alertsMuted(carContext)
- if (nowMuted) com.rfsentinel.app.util.Voice.silence()
- Prefs.setAlertsMuted(carContext, nowMuted)
- // Unmuting also ends a snooze: the driver wants sound back now.
- if (!nowMuted) Prefs.setAlertsSnoozedUntil(carContext, 0L)
- toast(if (nowMuted) "Alert sound muted" else "Alert sound on - plays through the car speakers")
- invalidate()
- }
- .build()
-
- return ListTemplate.Builder()
- .setTitle("RF Sentinel")
- .setHeaderAction(Action.APP_ICON)
- .setActionStrip(ActionStrip.Builder().addAction(startStop).addAction(muteButton).build())
- .setSingleList(items.build())
- .build()
+ val muteButton = action(icon = if (muted) R.drawable.ic_car_volume_off else R.drawable.ic_car_volume) {
+ val nowMuted = !Prefs.alertsMuted(carContext)
+ if (nowMuted) com.rfsentinel.app.util.Voice.silence()
+ Prefs.setAlertsMuted(carContext, nowMuted)
+ if (!nowMuted) Prefs.setAlertsSnoozedUntil(carContext, 0L)
+ toast(if (nowMuted) "Alert sound muted" else "Alert sound on - plays through the car speakers")
+ invalidate()
+ }
+ return listTemplate("RF Sentinel", shown, header = Action.APP_ICON,
+ actions = ActionStrip.Builder().addAction(startStop).addAction(muteButton).build())
}
private fun start() {
diff --git a/app/src/main/java/com/rfsentinel/app/car/LiveMapScreen.kt b/app/src/main/java/com/rfsentinel/app/car/LiveMapScreen.kt
index 3e1cfc6..67db60b 100644
--- a/app/src/main/java/com/rfsentinel/app/car/LiveMapScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/LiveMapScreen.kt
@@ -4,8 +4,6 @@ import androidx.car.app.AppManager
import androidx.car.app.CarContext
import androidx.car.app.model.Action
import androidx.car.app.model.ActionStrip
-import androidx.car.app.model.ItemList
-import androidx.car.app.model.ListTemplate
import androidx.car.app.model.Row
import androidx.car.app.model.Template
import androidx.car.app.navigation.model.MapController
@@ -59,82 +57,50 @@ class LiveMapScreen(carContext: CarContext) : LiveScreen(carContext, periodMs =
}
override fun render(): Template {
- val list = ItemList.Builder()
- if (Navigator.active) guidanceRows(list) else summaryRows(list)
-
- val content = ListTemplate.Builder()
- .setTitle(if (Navigator.active) Navigator.destination?.name ?: "Navigation" else "Live map")
- .setHeaderAction(Action.BACK)
- .setSingleList(list.build())
- .build()
-
- // Map buttons: PAN (lets the car send drags), zoom, and back to following the car.
+ val content = listTemplate(
+ if (Navigator.active) Navigator.destination?.name ?: "Navigation" else "Live map",
+ if (Navigator.active) guidanceRows() else summaryRows()
+ )
+ // PAN lets the car send drags. The other buttons zoom and resume following.
val mapActions = ActionStrip.Builder()
.addAction(Action.PAN)
- .addAction(Action.Builder().setIcon(CarUi.icon(carContext, R.drawable.ic_car_zoom_in))
- .setOnClickListener { renderer.zoomBy(1.0) }.build())
- .addAction(Action.Builder().setIcon(CarUi.icon(carContext, R.drawable.ic_car_zoom_out))
- .setOnClickListener { renderer.zoomBy(-1.0) }.build())
- .addAction(Action.Builder().setIcon(CarUi.icon(carContext, R.drawable.ic_car_my_location))
- .setOnClickListener { renderer.recenter(); invalidate() }.build())
+ .addAction(action(icon = R.drawable.ic_car_zoom_in) { renderer.zoomBy(1.0) })
+ .addAction(action(icon = R.drawable.ic_car_zoom_out) { renderer.zoomBy(-1.0) })
+ .addAction(action(icon = R.drawable.ic_car_my_location) { renderer.recenter(); invalidate() })
.build()
-
return MapWithContentTemplate.Builder()
.setContentTemplate(content)
.setMapController(MapController.Builder().setMapActionStrip(mapActions).build())
.build()
}
- private fun summaryRows(list: ItemList.Builder) {
+ private fun summaryRows(): List<Row> {
val (devices, cameras) = renderer.counts()
- list.addItem(Row.Builder()
- .setTitle(if (ScanForegroundService.isRunning) "$devices device${if (devices == 1) "" else "s"} · $cameras camera${if (cameras == 1) "" else "s"} on the map" else "Not scanning")
- .addText(if (renderer.following) "Drag or pinch the map to look around" else "Tap ◎ to follow the car again")
- .build())
- list.addItem(Row.Builder()
- .setTitle("Navigate to...")
- .addText("Search a destination (OpenStreetMap data)")
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_navigate))
- .setBrowsable(true)
- .setOnClickListener { screenManager.push(DestinationScreen(carContext, this)) }
- .build())
- list.addItem(Row.Builder()
- .setTitle("Device list")
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_list))
- .setBrowsable(true)
- .setOnClickListener { screenManager.push(DevicesMapScreen(carContext)) }
- .build())
- list.addItem(Row.Builder()
- .setTitle("Camera list")
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_warning))
- .setBrowsable(true)
- .setOnClickListener { screenManager.push(NearbyMapScreen(carContext)) }
- .build())
+ return listOf(
+ row(if (ScanForegroundService.isRunning) "$devices device${if (devices == 1) "" else "s"} · $cameras camera${if (cameras == 1) "" else "s"} on the map" else "Not scanning",
+ if (renderer.following) "Drag or pinch the map to look around" else "Tap ◎ to follow the car again"),
+ row("Navigate to...", "Search a destination (OpenStreetMap data)",
+ icon = R.drawable.ic_car_navigate, browsable = true) { screenManager.push(DestinationScreen(carContext, this)) },
+ row("Device list", icon = R.drawable.ic_view_list, browsable = true) { screenManager.push(DevicesMapScreen(carContext)) },
+ row("Camera list", icon = R.drawable.ic_car_warning, browsable = true) { screenManager.push(NearbyMapScreen(carContext)) }
+ )
}
- private fun guidanceRows(list: ItemList.Builder) {
+ private fun guidanceRows(): List<Row> {
val s = Navigator.state
val r = Navigator.route
- // The banner's own wording for the coming turn ("Rue Principale"), else Valhalla's sentence for the next step.
val banner = if (r != null && s != null) com.rfsentinel.app.nav.Prompts.banner(r, s.stepIndex, s.toManeuverM) else null
val next = r?.steps?.getOrNull((s?.stepIndex ?: 0) + 1)
val turn = banner?.text?.takeIf { it.isNotBlank() } ?: next?.instruction?.removeSuffix(".")
- list.addItem(Row.Builder()
- .setTitle(Navigator.status ?: turn ?: "Follow the route")
- .addText(if (s != null) "in ${NearbyMapScreen.distanceText(s.toManeuverM)}" else "Waiting for GPS...")
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_navigate))
- .build())
+ val rows = mutableListOf(row(Navigator.status ?: turn ?: "Follow the route",
+ if (s != null) "in ${NearbyMapScreen.distanceText(s.toManeuverM)}" else "Waiting for GPS...",
+ icon = R.drawable.ic_car_navigate))
if (s != null) {
val left = Navigator.remainingS ?: s.remainingS
val eta = DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(System.currentTimeMillis() + (left * 1000).toLong()))
- list.addItem(Row.Builder()
- .setTitle("Arrive $eta")
- .addText("${NearbyMapScreen.distanceText(s.remainingM)} · ${com.rfsentinel.app.nav.NavFormat.duration(left)}")
- .build())
+ rows += row("Arrive $eta", "${NearbyMapScreen.distanceText(s.remainingM)} · ${com.rfsentinel.app.nav.NavFormat.duration(left)}")
}
- list.addItem(Row.Builder()
- .setTitle("Stop navigation")
- .setOnClickListener { Navigator.stop(); renderer.recenter(); invalidate() }
- .build())
+ rows += row("Stop navigation") { Navigator.stop(); renderer.recenter(); invalidate() }
+ return rows
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/car/LiveScreen.kt b/app/src/main/java/com/rfsentinel/app/car/LiveScreen.kt
index f3b2f87..fb25baf 100644
--- a/app/src/main/java/com/rfsentinel/app/car/LiveScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/LiveScreen.kt
@@ -1,10 +1,25 @@
package com.rfsentinel.app.car
import android.util.Log
+import android.location.Location
+import android.text.SpannableString
+import android.text.Spanned
+import androidx.annotation.DrawableRes
import androidx.car.app.CarContext
import androidx.car.app.Screen
import androidx.car.app.model.Action
+import androidx.car.app.model.ActionStrip
+import androidx.car.app.model.CarColor
+import androidx.car.app.model.CarLocation
+import androidx.car.app.model.DistanceSpan
+import androidx.car.app.model.ItemList
+import androidx.car.app.model.ListTemplate
import androidx.car.app.model.MessageTemplate
+import androidx.car.app.model.Metadata
+import androidx.car.app.model.Place
+import androidx.car.app.model.PlaceListMapTemplate
+import androidx.car.app.model.PlaceMarker
+import androidx.car.app.model.Row
import androidx.car.app.model.Template
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
@@ -19,6 +34,61 @@ import kotlinx.coroutines.launch
*/
abstract class SafeScreen(carContext: CarContext) : Screen(carContext) {
+ protected fun row(
+ title: CharSequence, vararg text: CharSequence, @DrawableRes icon: Int? = null,
+ color: Int? = null, browsable: Boolean = false, onClick: (() -> Unit)? = null
+ ): Row = Row.Builder().setTitle(title).apply {
+ text.forEach { addText(it) }
+ icon?.let { setImage(CarUi.icon(carContext, it, color)) }
+ if (browsable) setBrowsable(true)
+ onClick?.let { setOnClickListener { it() } }
+ }.build()
+
+ protected fun action(title: String? = null, @DrawableRes icon: Int? = null, onClick: () -> Unit): Action =
+ Action.Builder().apply {
+ title?.let { setTitle(it) }
+ icon?.let { setIcon(CarUi.icon(carContext, it)) }
+ setOnClickListener { onClick() }
+ }.build()
+
+ protected fun itemList(rows: List<Row>, noItems: String? = null): ItemList = ItemList.Builder().apply {
+ rows.forEach { addItem(it) }
+ noItems?.let { setNoItemsMessage(it) }
+ }.build()
+
+ @Suppress("DEPRECATION") // Older Android Auto hosts use these title/header APIs.
+ protected fun listTemplate(
+ title: String, rows: List<Row>, noItems: String? = null,
+ header: Action = Action.BACK, actions: ActionStrip? = null
+ ): ListTemplate = ListTemplate.Builder().setTitle(title).setHeaderAction(header)
+ .setSingleList(itemList(rows, noItems)).apply { actions?.let { setActionStrip(it) } }.build()
+
+ protected fun mapTemplate(
+ title: String, rows: List<Row>, action: Action, location: Location? = null, noItems: String? = null
+ ): PlaceListMapTemplate = PlaceListMapTemplate.Builder()
+ .setTitle(title).setHeaderAction(Action.BACK).setCurrentLocationEnabled(location != null)
+ .setActionStrip(ActionStrip.Builder().addAction(action).build())
+ .setItemList(itemList(rows, noItems)).apply {
+ location?.let { setAnchor(Place.Builder(CarLocation.create(it.latitude, it.longitude)).build()) }
+ }.build()
+
+ protected fun mapRow(
+ title: String, detail: String, lat: Double, lon: Double, distanceM: Double?,
+ color: CarColor, label: String?, onClick: (() -> Unit)? = null
+ ): Row {
+ val marker = PlaceMarker.Builder().setColor(color).apply { label?.let { setLabel(it) } }.build()
+ val place = Place.Builder(CarLocation.create(lat, lon)).setMarker(marker).build()
+ // The host formats the distance. Rows without one must be browsable.
+ val text = if (distanceM == null) detail else SpannableString(" · $detail").apply {
+ setSpan(DistanceSpan.create(NearbyMapScreen.distanceOf(distanceM)), 0, 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
+ }
+ return Row.Builder().setTitle(title).addText(text).setMetadata(Metadata.Builder().setPlace(place).build())
+ .apply {
+ if (distanceM == null) setBrowsable(true)
+ onClick?.let { setOnClickListener { it() } }
+ }.build()
+ }
+
/** Builds this screen's template (may throw; [onGetTemplate] catches it). */
protected abstract fun buildTemplate(): Template
diff --git a/app/src/main/java/com/rfsentinel/app/car/MoreScreen.kt b/app/src/main/java/com/rfsentinel/app/car/MoreScreen.kt
index 34b6b24..b10ca8b 100644
--- a/app/src/main/java/com/rfsentinel/app/car/MoreScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/MoreScreen.kt
@@ -2,10 +2,6 @@ package com.rfsentinel.app.car
import androidx.car.app.CarContext
import androidx.car.app.CarToast
-import androidx.car.app.model.Action
-import androidx.car.app.model.ItemList
-import androidx.car.app.model.ListTemplate
-import androidx.car.app.model.Row
import androidx.car.app.model.Template
import com.rfsentinel.app.R
import com.rfsentinel.app.receiver.AlertActionReceiver
@@ -23,21 +19,16 @@ class MoreScreen(carContext: CarContext) : LiveScreen(carContext, periodMs = 5_0
Prefs.excludeAirTags(carContext), CellsScreen.summary()
)
- @Suppress("DEPRECATION") // setTitle keeps compatibility with older Android Auto hosts
override fun render(): Template {
- val now = System.currentTimeMillis()
- val snoozed = now < Prefs.alertsSnoozedUntil(carContext)
+ val snoozed = System.currentTimeMillis() < Prefs.alertsSnoozedUntil(carContext)
val mins = Prefs.snoozeMinutes(carContext)
val voice = Prefs.carVoice(carContext)
val short = Prefs.shortVoice(carContext)
val noAirTags = Prefs.excludeAirTags(carContext)
- val items = ItemList.Builder()
-
- items.addItem(Row.Builder()
- .setTitle(if (snoozed) "Resume alert sound" else "Snooze alerts $mins min")
- .addText(if (snoozed) CarUi.silencedText(carContext) else "No alert sound or voice for $mins minutes")
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_snooze))
- .setOnClickListener {
+ val rows = listOf(
+ row(if (snoozed) "Resume alert sound" else "Snooze alerts $mins min",
+ if (snoozed) CarUi.silencedText(carContext) else "No alert sound or voice for $mins minutes",
+ icon = R.drawable.ic_car_snooze) {
if (snoozed) {
Prefs.setAlertsSnoozedUntil(carContext, 0L)
toast("Alert sound back on")
@@ -46,60 +37,32 @@ class MoreScreen(carContext: CarContext) : LiveScreen(carContext, periodMs = 5_0
toast("Alerts snoozed for $mins minutes")
}
invalidate()
- }
- .build())
-
- items.addItem(Row.Builder()
- .setTitle("Spoken alerts in car: ${if (voice) "On" else "Off"}")
- .addText(if (voice) "Says what was detected - tap to turn off" else "Tone only - tap to hear what was detected")
- .setImage(CarUi.icon(carContext, if (voice) R.drawable.ic_car_voice else R.drawable.ic_car_voice_off))
- .setOnClickListener { Prefs.setCarVoice(carContext, !voice); invalidate() }
- .build())
-
- items.addItem(Row.Builder()
- .setTitle("Short spoken alerts: ${if (short) "On" else "Off"}")
- .addText(if (short) "\"Body cam\", \"Police car\", \"Speed camera, 50\"" else "Full labels, e.g. \"Axon body camera nearby\"")
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_voice))
- .setOnClickListener {
+ },
+ row("Spoken alerts in car: ${if (voice) "On" else "Off"}",
+ if (voice) "Says what was detected - tap to turn off" else "Tone only - tap to hear what was detected",
+ icon = if (voice) R.drawable.ic_car_voice else R.drawable.ic_car_voice_off) {
+ Prefs.setCarVoice(carContext, !voice)
+ invalidate()
+ },
+ row("Short spoken alerts: ${if (short) "On" else "Off"}",
+ if (short) "\"Body cam\", \"Police car\", \"Speed camera, 50\"" else "Full labels, e.g. \"Axon body camera nearby\"",
+ icon = R.drawable.ic_car_voice) {
Prefs.setShortVoice(carContext, !short)
com.rfsentinel.app.util.AlertPlayer.testVoice(carContext, !short)
invalidate()
+ },
+ row("Cell towers", CellsScreen.summary() ?: "Serving cell, neighbours and fake-cell checks",
+ icon = R.drawable.ic_car_tower, browsable = true) { screenManager.push(CellsScreen(carContext)) },
+ row("Hardware", "ESP32, Marauder, OUI-SPY, USB WiFi adapter",
+ icon = R.drawable.ic_car_usb, browsable = true) { screenManager.push(HardwareScreen(carContext)) },
+ row("AirTags count as trackers: ${if (noAirTags) "No" else "Yes"}",
+ if (noAirTags) "Apple Find My tags are left out - tap to include" else "Tap to leave Apple Find My tags out",
+ icon = R.drawable.ic_car_drone) {
+ Prefs.setExcludeAirTags(carContext, !noAirTags)
+ invalidate()
}
- .build())
-
- items.addItem(Row.Builder()
- .setTitle("Cell towers")
- .addText(CellsScreen.summary() ?: "Serving cell, neighbours and fake-cell checks")
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_tower))
- .setBrowsable(true)
- .setOnClickListener { screenManager.push(CellsScreen(carContext)) }
- .build())
-
- items.addItem(Row.Builder()
- .setTitle("Hardware")
- .addText("ESP32, Marauder, OUI-SPY, USB WiFi adapter")
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_usb))
- .setBrowsable(true)
- .setOnClickListener { screenManager.push(HardwareScreen(carContext)) }
- .build())
-
- items.addItem(Row.Builder()
- .setTitle("AirTags count as trackers: ${if (noAirTags) "No" else "Yes"}")
- .addText(if (noAirTags) "Apple Find My tags are left out - tap to include" else "Tap to leave Apple Find My tags out")
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_drone))
- .setOnClickListener { Prefs.setExcludeAirTags(carContext, !noAirTags); invalidate() }
- .build())
-
- val list = ItemList.Builder()
- // Keep the car's row limit (the order above is by importance).
- val built = items.build().items.take(CarUi.listLimit(carContext))
- built.forEach { list.addItem(it) }
-
- return ListTemplate.Builder()
- .setTitle("More")
- .setHeaderAction(Action.BACK)
- .setSingleList(list.build())
- .build()
+ )
+ return listTemplate("More", rows.take(CarUi.listLimit(carContext)))
}
private fun toast(msg: String) = CarToast.makeText(carContext, msg, CarToast.LENGTH_SHORT).show()
diff --git a/app/src/main/java/com/rfsentinel/app/car/NearbyDevicesScreen.kt b/app/src/main/java/com/rfsentinel/app/car/NearbyDevicesScreen.kt
index 9df7664..9fcf025 100644
--- a/app/src/main/java/com/rfsentinel/app/car/NearbyDevicesScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/NearbyDevicesScreen.kt
@@ -1,10 +1,6 @@
package com.rfsentinel.app.car
import androidx.car.app.CarContext
-import androidx.car.app.model.Action
-import androidx.car.app.model.ItemList
-import androidx.car.app.model.ListTemplate
-import androidx.car.app.model.Row
import androidx.car.app.model.Template
import com.rfsentinel.app.R
import com.rfsentinel.app.service.DeviceRegistry
@@ -24,31 +20,18 @@ class NearbyDevicesScreen(carContext: CarContext) : LiveScreen(carContext) {
override fun contentKey(): Any = listOf(ScanForegroundService.isRunning, counts())
- @Suppress("DEPRECATION") // setTitle keeps compatibility with older Android Auto hosts
- override fun render(): Template {
- val items = ItemList.Builder()
- counts().take(CarUi.listLimit(carContext)).forEach { (f, n) ->
- items.addItem(
- Row.Builder()
- .setTitle("${DeviceListScreen.titleOf(f)} ($n)")
- .setImage(CarUi.icon(carContext, iconOf(f)))
- .setBrowsable(true)
- .setOnClickListener { screenManager.push(DeviceListScreen(carContext, f)) }
- .build()
- )
- }
- return ListTemplate.Builder()
- .setTitle("Nearby devices")
- .setHeaderAction(Action.BACK)
- .setSingleList(items.build())
- .build()
- }
+ override fun render(): Template = listTemplate("Nearby devices",
+ counts().take(CarUi.listLimit(carContext)).map { (f, n) ->
+ row("${DeviceListScreen.titleOf(f)} ($n)", icon = iconOf(f), browsable = true) {
+ screenManager.push(DeviceListScreen(carContext, f))
+ }
+ })
private fun iconOf(f: DeviceFilter) = when (f) {
DeviceFilter.FLAGGED -> R.drawable.ic_car_warning
DeviceFilter.TRACKERS, DeviceFilter.DRONES -> R.drawable.ic_car_drone
DeviceFilter.FAVORITES -> R.drawable.ic_car_star
DeviceFilter.EXTERNAL -> R.drawable.ic_car_usb
- else -> R.drawable.ic_car_list
+ else -> R.drawable.ic_view_list
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/car/NearbyMapScreen.kt b/app/src/main/java/com/rfsentinel/app/car/NearbyMapScreen.kt
index 686e87d..06f0bbf 100644
--- a/app/src/main/java/com/rfsentinel/app/car/NearbyMapScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/NearbyMapScreen.kt
@@ -1,25 +1,13 @@
package com.rfsentinel.app.car
-import android.annotation.SuppressLint
import android.location.Location
-import android.location.LocationManager
import androidx.car.app.CarContext
-import androidx.car.app.CarToast
-import androidx.car.app.model.Action
import androidx.car.app.model.CarColor
-import androidx.car.app.model.CarLocation
-import androidx.car.app.model.ItemList
-import androidx.car.app.model.Metadata
-import androidx.car.app.model.Place
-import androidx.car.app.model.PlaceListMapTemplate
-import androidx.car.app.model.PlaceMarker
import androidx.car.app.model.Row
import androidx.car.app.model.Template
import com.rfsentinel.app.alpr.AlprStore
import com.rfsentinel.app.alpr.KnownCameras
import com.rfsentinel.app.service.DeviceRegistry
-import com.rfsentinel.app.service.ScanForegroundService
-import com.rfsentinel.app.util.Permissions
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
@@ -57,32 +45,15 @@ class NearbyMapScreen(
val limit = CarUi.listLimit(carContext).coerceAtMost(6)
val items = if (me == null) emptyList() else nearby(me.latitude, me.longitude, limit)
- val list = ItemList.Builder()
- if (me == null) {
- list.setNoItemsMessage("Waiting for your location...")
- } else if (items.isEmpty()) {
- list.setNoItemsMessage(
- if (AlprStore.cameras.isEmpty()) "No known cameras downloaded - on your phone: Map > menu > Download nearby cameras"
- else "No known cameras or drones within ${com.rfsentinel.app.util.Units.km((SEARCH_RADIUS_M / 1000).toInt())}"
- )
+ val noItems = when {
+ me == null -> "Waiting for your location..."
+ items.isNotEmpty() -> null
+ AlprStore.cameras.isEmpty() -> "No known cameras downloaded - on your phone: Map > menu > Download nearby cameras"
+ else -> "No known cameras or drones within ${com.rfsentinel.app.util.Units.km((SEARCH_RADIUS_M / 1000).toInt())}"
}
- items.forEach { it -> list.addItem(row(it)) }
-
- val template = PlaceListMapTemplate.Builder()
- .setTitle("Cameras nearby")
- .setHeaderAction(Action.BACK)
- .setActionStrip(
- androidx.car.app.model.ActionStrip.Builder().addAction(
- Action.Builder().setTitle("Devices").setOnClickListener {
- if (fromDevicesMap) screenManager.pop() else screenManager.push(DevicesMapScreen(carContext))
- }.build()
- ).build()
- )
- .setCurrentLocationEnabled(me != null)
- .setItemList(list.build())
- // Centre on the driver, not on 0°,0°, when there is nothing to show.
- if (me != null) template.setAnchor(Place.Builder(CarLocation.create(me.latitude, me.longitude)).build())
- return template.build()
+ return mapTemplate("Cameras nearby", items.map { row(it) }, action("Devices") {
+ if (fromDevicesMap) screenManager.pop() else screenManager.push(DevicesMapScreen(carContext))
+ }, location = me, noItems = noItems)
}
private fun row(it: Item): Row {
@@ -95,24 +66,11 @@ class NearbyMapScreen(
else -> CarColor.YELLOW
}
val label = it.kind?.let { k -> cameraLabel(k) } ?: if (it.drone) "D" else "!"
- val place = Place.Builder(CarLocation.create(it.lat, it.lon))
- .setMarker(PlaceMarker.Builder().setColor(color).setLabel(label).build())
- .build()
- // Android Auto requires every place row on a map template to carry its distance
- // as a DistanceSpan (the host formats it in the driver's units); plain text throws.
- val text = android.text.SpannableString(" · " + it.detail + if (ignored) " · alerts off" else "")
- text.setSpan(androidx.car.app.model.DistanceSpan.create(distanceOf(it.distanceM)), 0, 1,
- android.text.Spanned.SPAN_INCLUSIVE_INCLUSIVE)
- return Row.Builder()
- .setTitle(it.title)
- .addText(text)
- .setMetadata(Metadata.Builder().setPlace(place).build())
- .setOnClickListener {
- if (it.mac != null) screenManager.push(DeviceDetailScreen(carContext, it.mac))
- else if (it.camera != null) screenManager.push(PlaceFocusScreen.forCamera(carContext, it.camera))
- else screenManager.push(PlaceFocusScreen(carContext, it.title, it.detail, it.lat, it.lon, color, label))
- }
- .build()
+ return mapRow(it.title, it.detail + if (ignored) " · alerts off" else "", it.lat, it.lon, it.distanceM, color, label) {
+ if (it.mac != null) screenManager.push(DeviceDetailScreen(carContext, it.mac))
+ else if (it.camera != null) screenManager.push(PlaceFocusScreen.forCamera(carContext, it.camera))
+ else screenManager.push(PlaceFocusScreen(carContext, it.title, it.detail, it.lat, it.lon, color, label))
+ }
}
/** Fetches the cameras within ~20 km when that area isn't cached yet, then refreshes. */
diff --git a/app/src/main/java/com/rfsentinel/app/car/PlaceFocusScreen.kt b/app/src/main/java/com/rfsentinel/app/car/PlaceFocusScreen.kt
index 2e290ce..bf65604 100644
--- a/app/src/main/java/com/rfsentinel/app/car/PlaceFocusScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/PlaceFocusScreen.kt
@@ -1,20 +1,8 @@
package com.rfsentinel.app.car
-import android.text.SpannableString
-import android.text.Spanned
import androidx.car.app.CarContext
import androidx.car.app.CarToast
-import androidx.car.app.model.Action
-import androidx.car.app.model.ActionStrip
import androidx.car.app.model.CarColor
-import androidx.car.app.model.CarLocation
-import androidx.car.app.model.DistanceSpan
-import androidx.car.app.model.ItemList
-import androidx.car.app.model.Metadata
-import androidx.car.app.model.Place
-import androidx.car.app.model.PlaceListMapTemplate
-import androidx.car.app.model.PlaceMarker
-import androidx.car.app.model.Row
import androidx.car.app.model.Template
import com.rfsentinel.app.R
import com.rfsentinel.app.alpr.IgnoredCameras
@@ -50,23 +38,14 @@ class PlaceFocusScreen(
override fun render(): Template {
val me = CarUi.currentLocation(carContext)
val ignored = cameraId?.let { IgnoredCameras.contains(carContext, it) } ?: false
- val marker = PlaceMarker.Builder().setColor(if (ignored) IGNORED_COLOR else color)
- label?.let { marker.setLabel(it) }
- val place = Place.Builder(CarLocation.create(lat, lon)).setMarker(marker.build()).build()
-
val shownDetail = when {
- cameraId == null -> detail
+ me == null || cameraId == null -> detail
ignored -> "Alerts off - tap to turn them back on"
else -> "$detail · tap to ignore its alerts"
}
- val row = Row.Builder().setTitle(title).setMetadata(Metadata.Builder().setPlace(place).build())
- if (me != null) {
- // Map rows carry their distance as a DistanceSpan (the car formats it).
- val text = SpannableString(" · $shownDetail")
- val d = DeviceRegistry.metersBetween(me.latitude, me.longitude, lat, lon)
- text.setSpan(DistanceSpan.create(NearbyMapScreen.distanceOf(d)), 0, 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
- row.addText(text)
- if (cameraId != null) row.setOnClickListener {
+ val navigate = { CarUi.navigateTo(carContext, lat, lon) }
+ val toggle: (() -> Unit)? = if (cameraId == null) null else {
+ {
val nowIgnored = !IgnoredCameras.contains(carContext, cameraId)
IgnoredCameras.set(carContext, cameraId, nowIgnored)
CarToast.makeText(carContext,
@@ -74,30 +53,12 @@ class PlaceFocusScreen(
CarToast.LENGTH_SHORT).show()
invalidate()
}
- } else {
- // No position yet, so no distance: Android Auto only accepts a map row
- // without a DistanceSpan when it's browsable - let it start navigation.
- row.addText(detail)
- .setBrowsable(true)
- .setOnClickListener { CarUi.navigateTo(carContext, lat, lon) }
}
-
- return PlaceListMapTemplate.Builder()
- .setTitle(title)
- .setHeaderAction(Action.BACK)
- // Your own position off, so the map frames this place rather than both of you.
- .setCurrentLocationEnabled(false)
- .setActionStrip(
- ActionStrip.Builder().addAction(
- Action.Builder()
- .setTitle("Navigate")
- .setIcon(CarUi.icon(carContext, R.drawable.ic_car_navigate))
- .setOnClickListener { CarUi.navigateTo(carContext, lat, lon) }
- .build()
- ).build()
- )
- .setItemList(ItemList.Builder().addItem(row.build()).build())
- .build()
+ val row = mapRow(title, shownDetail, lat, lon,
+ me?.let { DeviceRegistry.metersBetween(it.latitude, it.longitude, lat, lon) },
+ if (ignored) IGNORED_COLOR else color, label, if (me == null) navigate else toggle)
+ // No current-location marker or anchor, so the host frames this place alone.
+ return mapTemplate(title, listOf(row), action("Navigate", R.drawable.ic_car_navigate, navigate))
}
companion object {
diff --git a/app/src/main/java/com/rfsentinel/app/car/RecentAlertsScreen.kt b/app/src/main/java/com/rfsentinel/app/car/RecentAlertsScreen.kt
index 8cf6eeb..9c355eb 100644
--- a/app/src/main/java/com/rfsentinel/app/car/RecentAlertsScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/RecentAlertsScreen.kt
@@ -1,11 +1,7 @@
package com.rfsentinel.app.car
import androidx.car.app.CarContext
-import androidx.car.app.model.Action
import androidx.car.app.model.CarColor
-import androidx.car.app.model.ItemList
-import androidx.car.app.model.ListTemplate
-import androidx.car.app.model.Row
import androidx.car.app.model.Template
import com.rfsentinel.app.R
import com.rfsentinel.app.alpr.AlprStore
@@ -28,32 +24,19 @@ class RecentAlertsScreen(carContext: CarContext) : LiveScreen(carContext, period
return entries().map { "${it.key}|${it.time}|${CarUi.ageText(now - it.time)}" }
}
- @Suppress("DEPRECATION") // setTitle keeps compatibility with older Android Auto hosts
override fun render(): Template {
val now = System.currentTimeMillis()
val me = CarUi.currentLocation(carContext)
- val items = ItemList.Builder()
- entries().forEach { e ->
- val color = when {
- e.tierEnum == Tier.WEAK -> CarUi.WEAK_COLOR
- else -> e.categoryEnum?.colorArgb ?: CarUi.DANGER_COLOR
- }
+ return listTemplate("Recent alerts", entries().map { e ->
+ val color = if (e.tierEnum == Tier.WEAK) CarUi.WEAK_COLOR else e.categoryEnum?.colorArgb ?: CarUi.DANGER_COLOR
val where = if (me != null && e.lat != null && e.lon != null)
" · " + NearbyMapScreen.distanceText(DeviceRegistry.metersBetween(me.latitude, me.longitude, e.lat, e.lon)) + " away"
else ""
- val row = Row.Builder()
- .setTitle((if (e.following) "FOLLOWING · " else "") + e.label)
- .addText("${e.categoryEnum?.shortTag ?: "Alert"} · ${CarUi.ageText(now - e.time)}$where")
- .setImage(CarUi.icon(carContext, R.drawable.ic_car_warning, color))
- target(e, CarColor.createCustom(color, color))?.let { open -> row.setOnClickListener { open() } }
- items.addItem(row.build())
- }
- items.setNoItemsMessage("No alerts yet")
- return ListTemplate.Builder()
- .setTitle("Recent alerts")
- .setHeaderAction(Action.BACK)
- .setSingleList(items.build())
- .build()
+ row((if (e.following) "FOLLOWING · " else "") + e.label,
+ "${e.categoryEnum?.shortTag ?: "Alert"} · ${CarUi.ageText(now - e.time)}$where",
+ icon = R.drawable.ic_car_warning, color = color,
+ onClick = target(e, CarColor.createCustom(color, color)))
+ }, "No alerts yet")
}
/** Where tapping an alert goes, or null when there is nothing more to show. */
diff --git a/app/src/main/java/com/rfsentinel/app/car/TrackerIgnoreScreen.kt b/app/src/main/java/com/rfsentinel/app/car/TrackerIgnoreScreen.kt
index cdc9a6c..d091ce2 100644
--- a/app/src/main/java/com/rfsentinel/app/car/TrackerIgnoreScreen.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/TrackerIgnoreScreen.kt
@@ -2,10 +2,6 @@ package com.rfsentinel.app.car
import androidx.car.app.CarContext
import androidx.car.app.CarToast
-import androidx.car.app.model.Action
-import androidx.car.app.model.ItemList
-import androidx.car.app.model.ListTemplate
-import androidx.car.app.model.Row
import androidx.car.app.model.Template
import com.rfsentinel.app.data.TrackerMutes
import com.rfsentinel.app.service.DeviceRegistry
@@ -18,33 +14,18 @@ import com.rfsentinel.app.util.Prefs
*/
class TrackerIgnoreScreen(carContext: CarContext, private val mac: String) : SafeScreen(carContext) {
- @Suppress("DEPRECATION") // setTitle keeps compatibility with older Android Auto hosts
- override fun buildTemplate(): Template {
- val items = ItemList.Builder()
- items.addItem(Row.Builder()
- .setTitle("It's mine - keep ignoring it")
- .addText("Follows it when its address changes (best effort)")
- .setOnClickListener { mute(follow = true, "Ignored - followed when its address changes") }
- .build())
- items.addItem(Row.Builder()
- .setTitle("Ignore it today only")
- .addText("Until its address changes, at most 24 h")
- .setOnClickListener { mute(follow = false, "Ignored until its address changes (at most 24 h)") }
- .build())
- items.addItem(Row.Builder()
- .setTitle("Pause all tracker follow warnings for 24 h")
- .addText("Only ignore a tag you know - a hidden tracker would stay silent too")
- .setOnClickListener {
- Prefs.setTrackerFollowPausedUntil(carContext, System.currentTimeMillis() + 24 * 3_600_000L)
- done("Tracker follow warnings paused for 24 hours")
- }
- .build())
- return ListTemplate.Builder()
- .setTitle("Ignore this tracker?")
- .setHeaderAction(Action.BACK)
- .setSingleList(items.build())
- .build()
- }
+ override fun buildTemplate(): Template = listTemplate("Ignore this tracker?", listOf(
+ row("It's mine - keep ignoring it", "Follows it when its address changes (best effort)") {
+ mute(follow = true, "Ignored - followed when its address changes")
+ },
+ row("Ignore it today only", "Until its address changes, at most 24 h") {
+ mute(follow = false, "Ignored until its address changes (at most 24 h)")
+ },
+ row("Pause all tracker follow warnings for 24 h", "Only ignore a tag you know - a hidden tracker would stay silent too") {
+ Prefs.setTrackerFollowPausedUntil(carContext, System.currentTimeMillis() + 24 * 3_600_000L)
+ done("Tracker follow warnings paused for 24 hours")
+ }
+ ))
private fun mute(follow: Boolean, message: String) {
val snap = DeviceRegistry.get(mac)
diff --git a/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt b/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt
index 30be96b..83cfe01 100644
--- a/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt
+++ b/app/src/main/java/com/rfsentinel/app/detect/DeviceIntel.kt
@@ -357,9 +357,11 @@ object DeviceIntel {
// Apple Continuity: manufacturer data is a list of [type][length][payload] TLVs.
a.manufacturerData[CID_APPLE]?.let { d ->
val found = mutableListOf<String>()
+ val types = HashSet<Int>()
var i = 0
while (i + 1 < d.size) {
val t = Bytes.u8(d, i)
+ types += t
val len = Bytes.u8(d, i + 1)
val name = APPLE_TYPES[t] ?: String.format("type 0x%02X", t)
found += name
@@ -388,15 +390,15 @@ object DeviceIntel {
if (found.isNotEmpty()) facts += "Apple Continuity" to found.distinct().joinToString()
if (basis == null) basis = "Apple Continuity message"
type = type ?: when {
- 0x07 in typesIn(d) -> "AirPods / Beats"
- 0x12 in typesIn(d) -> "Apple Find My device (AirTag, iPhone, Mac...)"
- 0x09 in typesIn(d) -> "Apple TV / AirPlay speaker"
+ 0x07 in types -> "AirPods / Beats"
+ 0x12 in types -> "Apple Find My device (AirTag, iPhone, Mac...)"
+ 0x09 in types -> "Apple TV / AirPlay speaker"
// Only a Watch reports being on a wrist or offers Magic Switch; only a phone drives,
// and only a phone or cellular iPad offers its hotspot.
- 0x0B in typesIn(d) || appleActivity(d) == 0x0A -> "Apple Watch"
+ 0x0B in types || appleActivity(d) == 0x0A -> "Apple Watch"
appleActivity(d) == 0x0D -> "iPhone"
- 0x0E in typesIn(d) -> "iPhone or cellular iPad"
- 0x10 in typesIn(d) || 0x0C in typesIn(d) -> "Apple device (iPhone, iPad, Mac or Watch)"
+ 0x0E in types -> "iPhone or cellular iPad"
+ 0x10 in types || 0x0C in types -> "Apple device (iPhone, iPad, Mac or Watch)"
else -> "Apple device"
}
}
@@ -474,18 +476,6 @@ object DeviceIntel {
return null
}
- private fun typesIn(d: ByteArray): Set<Int> {
- val out = HashSet<Int>()
- var i = 0
- while (i + 1 < d.size) {
- out += Bytes.u8(d, i)
- val len = Bytes.u8(d, i + 1)
- if (len == 0) break
- i += 2 + len
- }
- return out
- }
-
private val WIFI_VENDOR_KINDS = setOf(
"Vehicle / cellular router", "IoT / smart-home module", "Two-way radio / public-safety gear",
"Axon body cam / TASER", "Vehicle system", "Drone / controller", "Smart-home / camera device", "Rugged scanner / printer",
diff --git a/app/src/main/java/com/rfsentinel/app/nav/NavFormat.kt b/app/src/main/java/com/rfsentinel/app/nav/NavFormat.kt
index e74ccd0..c5fc067 100644
--- a/app/src/main/java/com/rfsentinel/app/nav/NavFormat.kt
+++ b/app/src/main/java/com/rfsentinel/app/nav/NavFormat.kt
@@ -81,16 +81,7 @@ object NavFormat {
}
/** The arrow for one lane direction ("straight", "slight right"...). */
- fun laneIcon(direction: String?): Icon = when (direction) {
- "left" -> Icon.LEFT
- "right" -> Icon.RIGHT
- "slight left" -> Icon.SLIGHT_LEFT
- "slight right" -> Icon.SLIGHT_RIGHT
- "sharp left" -> Icon.SHARP_LEFT
- "sharp right" -> Icon.SHARP_RIGHT
- "uturn" -> Icon.U_TURN_LEFT
- else -> Icon.STRAIGHT
- }
+ fun laneIcon(direction: String?): Icon = byModifier(direction)
/** The direction to draw for a lane: the one to take when it is the lane to be in, else its first. */
fun laneDirection(lane: Step.Lane): String? = if (lane.active) lane.activeDirection ?: lane.directions.firstOrNull() else lane.directions.firstOrNull()
diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtFetcher.java b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtFetcher.java
index 0c8888e..85c8332 100644
--- a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtFetcher.java
+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeRtFetcher.java
@@ -224,12 +224,6 @@ public final class WazeRtFetcher {
}
}
- /** Forget the session (not the account) so the next fetch logs in again. */
- public synchronized void reset() {
- session = null;
- cache.clear();
- }
-
// ── privacy: what position Waze gets ─────────────────────────────────────
/**
@@ -387,11 +381,6 @@ public final class WazeRtFetcher {
session = null;
}
- public synchronized boolean hasAccount() {
- String blob = SecureStore.INSTANCE.get(ctx, KEY_ACCOUNT);
- return blob != null && !blob.isEmpty();
- }
-
// ── registration cap + backoff ───────────────────────────────────────────
private SharedPreferences prefs() {
diff --git a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeSession.java b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeSession.java
index 1a53258..16180d1 100644
--- a/app/src/main/java/com/rfsentinel/app/online/wazert/WazeSession.java
+++ b/app/src/main/java/com/rfsentinel/app/online/wazert/WazeSession.java
@@ -9,9 +9,7 @@ import android.os.SystemClock;
import android.util.Log;
import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
import java.util.LinkedHashMap;
-import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -39,15 +37,7 @@ final class WazeSession {
/** Server session the handshake last ran on (0 = none), so it runs once per login. */
private long handshakedSessionId = 0L;
- WazeSession(String region) {
- this(region, DeviceIdentity.random(), null);
- }
-
- WazeSession(String region, DeviceIdentity device, WazeCredentials credentials) {
- this(region, device, credentials, new WazeHttpClient());
- }
-
- /** Test seam: same as above with the transport supplied by the caller. */
+ /** The caller supplies the session transport. */
WazeSession(String region, DeviceIdentity device, WazeCredentials credentials, WazeHttpClient http) {
this.region = region;
this.device = device;
@@ -61,10 +51,6 @@ final class WazeSession {
/** Server session id (0 if not logged in), lets the caller detect a re-login. */
long currentServerSessionId() { return session != null ? session.serverSessionId : 0L; }
- /** Drop the logged-in session but KEEP credentials, so the next call re-logs in
- * (with the in-memory account) instead of registering a brand-new one. */
- void invalidateSession() { session = null; }
-
/**
* Inspect a parsed response batch for in-band errors the server returns with an
* HTTP 200: a {@code ServerError} element, or a {@code LoginError}. Without this,
@@ -271,14 +257,4 @@ final class WazeSession {
WazeProto.Batch queryBox(double[] bbox) throws Exception {
return command(WazeRtCodec.mapDisplayedCommand(bbox[0], bbox[1], bbox[2], bbox[3]));
}
-
- /** Full flow for a single box: prepare + one query. Used by the debug selfTest. */
- List<WazeAlert> fetchArea(double lat, double lon, double radiusMeters) throws Exception {
- prepareForArea(lat, lon);
- double latDelta = radiusMeters / WazeConstants.M_PER_DEG_LAT;
- double lonDelta = radiusMeters / WazeConstants.mPerDegLon(lat);
- WazeProto.Batch batch = queryBox(new double[]{
- lon - lonDelta, lat - latDelta, lon + lonDelta, lat + latDelta});
- return WazeRtCodec.parseAlerts(batch);
- }
}
diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
index 33cc2f5..3112974 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -1077,25 +1077,24 @@ class ScanForegroundService : Service() {
val prevLogged = lastLogged[a.mac] ?: 0L
if (now - prevLogged < LOG_THROTTLE_MS) return
lastLogged[a.mac] = now
+ logDetection(a.mac, a.source.name, best, now, loc?.latitude, loc?.longitude,
+ rssi = a.rssi, vendor = vendor, deviceName = a.name,
+ radio = com.rfsentinel.app.detect.DeviceIntel.radioSummary(a))
+ }
+
+ private fun logDetection(
+ mac: String, source: String, hit: Hit, now: Long, latitude: Double?, longitude: Double?,
+ rssi: Int = 0, vendor: String? = null, deviceName: String? = null, radio: String? = null
+ ) {
val tag = Prefs.gpsTaggingEnabled(this)
+ val row = DetectionEntity(
+ mac = mac, label = hit.label, source = source, rssi = rssi, timestamp = now,
+ latitude = if (tag) latitude else null, longitude = if (tag) longitude else null,
+ category = hit.category.name, confidence = hit.confidence, evidence = hit.evidence,
+ vendor = vendor, deviceName = deviceName, radio = radio
+ )
serviceScope.launch {
- AppDatabase.getInstance(this@ScanForegroundService).detectionDao().insert(
- DetectionEntity(
- mac = a.mac,
- label = best.label,
- source = a.source.name,
- rssi = a.rssi,
- timestamp = now,
- latitude = if (tag) loc?.latitude else null,
- longitude = if (tag) loc?.longitude else null,
- category = best.category.name,
- confidence = best.confidence,
- evidence = best.evidence,
- vendor = vendor,
- deviceName = a.name,
- radio = com.rfsentinel.app.detect.DeviceIntel.radioSummary(a)
- )
- )
+ AppDatabase.getInstance(this@ScanForegroundService).detectionDao().insert(row)
}
}
@@ -1448,17 +1447,8 @@ class ScanForegroundService : Service() {
NotificationHelper.sendMapAlert(this, "cellchange", hit, com.rfsentinel.app.ui.CellTowersActivity::class.java, banner = AlertKind.BANNER !in off)
AlertPlayer.play(this, hit.tier, "Cell tower changed", off = off)
val loc = lastLocation
- val tag = Prefs.gpsTaggingEnabled(this)
- serviceScope.launch {
- AppDatabase.getInstance(this@ScanForegroundService).detectionDao().insert(
- DetectionEntity(
- mac = "CELL " + serving.key, label = hit.label, source = "CELL", rssi = serving.dbm ?: 0,
- timestamp = now,
- latitude = if (tag) loc?.latitude else null, longitude = if (tag) loc?.longitude else null,
- category = Category.CELL_ANOMALY.name, confidence = hit.confidence, evidence = detail
- )
- )
- }
+ logDetection("CELL " + serving.key, "CELL", hit, now, loc?.latitude, loc?.longitude,
+ rssi = serving.dbm ?: 0)
}
/**
@@ -1520,23 +1510,13 @@ class ScanForegroundService : Service() {
e.tdma -> "TETRA radio nearby"
else -> "Radio transmitting nearby"
} + (via?.let { ", via $it" } ?: "")
- radioDetection(hit, "RADIO " + e.mhz + " MHz", e.snrDb, detail, now, "radio:" + e.freqHz, spoken, e.confidence >= threshold)
+ radioDetection(hit, "RADIO " + e.mhz + " MHz", e.snrDb, now, "radio:" + e.freqHz, spoken, e.confidence >= threshold)
}
/** A radio [hit] into the detection history (tagged with where you are), and alerted when [alert]. */
- private fun radioDetection(hit: Hit, mac: String, rssi: Int, evidence: String, now: Long, key: String, spoken: String, alert: Boolean) {
+ private fun radioDetection(hit: Hit, mac: String, rssi: Int, now: Long, key: String, spoken: String, alert: Boolean) {
val loc = lastLocation
- val tag = Prefs.gpsTaggingEnabled(this)
- serviceScope.launch {
- AppDatabase.getInstance(this@ScanForegroundService).detectionDao().insert(
- DetectionEntity(
- mac = mac, label = hit.label, source = "SDR", rssi = rssi,
- timestamp = now,
- latitude = if (tag) loc?.latitude else null, longitude = if (tag) loc?.longitude else null,
- category = hit.category.name, confidence = hit.confidence, evidence = evidence
- )
- )
- }
+ logDetection(mac, "SDR", hit, now, loc?.latitude, loc?.longitude, rssi = rssi)
// Dismissed from the list (swiped left): logged, no alert.
if (!alert || com.rfsentinel.app.data.AlertMutes.isMuted(this, key, now)) return
val off = alertsOff(hit.category)
@@ -1558,7 +1538,7 @@ class ScanForegroundService : Service() {
(if (row?.encrypted == true) "Encrypted. " else "") +
"Heard on the site's control channel: the radios may be anywhere the site covers, not necessarily near you."
val hit = Hit(Category.RADIO, "Talkgroup active: $called", P25_CONFIDENCE, detail, "P25 control channel (signalling only, no voice)")
- radioDetection(hit, "P25 TG $tg", 0, detail, System.currentTimeMillis(), "p25:$tg", "Talkgroup $called active",
+ radioDetection(hit, "P25 TG $tg", 0, System.currentTimeMillis(), "p25:$tg", "Talkgroup $called active",
P25_CONFIDENCE >= Prefs.alertThreshold(this, Category.RADIO))
}
@@ -1582,7 +1562,7 @@ class ScanForegroundService : Service() {
(if (call.emergency) " Marked as an emergency call." else "") + (if (call.encrypted) " Encrypted." else "")
val hit = Hit(Category.RADIO, "P25 radio keyed up $near: $called", confidence, detail,
"P25 control channel grant + SDR signal strength on the input (no voice)")
- radioDetection(hit, "P25 radio ${call.source}", snr, detail, now, "p25in:${call.tg ?: call.target}",
+ radioDetection(hit, "P25 radio ${call.source}", snr, now, "p25in:${call.tg ?: call.target}",
"Radio keyed up $near, $called", confidence >= Prefs.alertThreshold(this, Category.RADIO))
}
@@ -1611,7 +1591,7 @@ class ScanForegroundService : Service() {
"Busier than usual can mean an incident, an event or a planned operation. Heard on the site's control channel: " +
"the radios may be anywhere the site covers."
val hit = Hit(Category.RADIO, "Unusual activity: $called", P25_UNUSUAL_CONFIDENCE, detail, "P25 call log (signalling only, no voice)")
- radioDetection(hit, "P25 TG ${u.tg}", 0, detail, now, "p25u:${u.tg}", "Unusual activity on $called",
+ radioDetection(hit, "P25 TG ${u.tg}", 0, now, "p25u:${u.tg}", "Unusual activity on $called",
P25_UNUSUAL_CONFIDENCE >= Prefs.alertThreshold(this, Category.RADIO))
}
@@ -1686,17 +1666,7 @@ class ScanForegroundService : Service() {
val now = System.currentTimeMillis()
val hit = Hit(Category.GNSS, a.title, a.confidence, a.detail, "Phone satellite receiver (heuristic, not proof)")
val loc = lastLocation
- val tag = Prefs.gpsTaggingEnabled(this)
- serviceScope.launch {
- AppDatabase.getInstance(this@ScanForegroundService).detectionDao().insert(
- DetectionEntity(
- mac = "GNSS " + a.key, label = a.title, source = "GNSS", rssi = 0,
- timestamp = now,
- latitude = if (tag) loc?.latitude else null, longitude = if (tag) loc?.longitude else null,
- category = Category.GNSS.name, confidence = a.confidence, evidence = a.detail
- )
- )
- }
+ logDetection("GNSS " + a.key, "GNSS", hit, now, loc?.latitude, loc?.longitude)
if (a.confidence >= Prefs.alertThreshold(this, hit.category)) {
val off = alertsOff(hit.category)
NotificationHelper.sendMapAlert(this, "gnss:" + a.key, hit, com.rfsentinel.app.ui.GnssActivity::class.java, banner = AlertKind.BANNER !in off)
@@ -1753,16 +1723,7 @@ class ScanForegroundService : Service() {
/** An attack heard over time rather than one device: logged, and alerted like a detection. */
private fun reportAttack(mac: String, source: String, hit: Hit, name: String?, key: String, spoken: String, now: Long) {
val loc = lastLocation
- val tag = Prefs.gpsTaggingEnabled(this)
- serviceScope.launch {
- AppDatabase.getInstance(this@ScanForegroundService).detectionDao().insert(
- DetectionEntity(
- mac = mac, label = hit.label, source = source, rssi = 0, timestamp = now,
- latitude = if (tag) loc?.latitude else null, longitude = if (tag) loc?.longitude else null,
- category = Category.HACKER.name, confidence = hit.confidence, evidence = hit.evidence, deviceName = name
- )
- )
- }
+ logDetection(mac, source, hit, now, loc?.latitude, loc?.longitude, deviceName = name)
if (hit.confidence >= Prefs.alertThreshold(this, hit.category)) {
val off = alertsOff(hit.category)
NotificationHelper.sendMapAlert(this, key, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java, banner = AlertKind.BANNER !in off)
@@ -1777,17 +1738,7 @@ class ScanForegroundService : Service() {
CellMonitor.lastAnomaly = now to a
val hit = Hit(Category.CELL_ANOMALY, a.title, a.confidence, a.detail, "Android cell info (heuristic, not proof)")
val loc = lastLocation
- val tag = Prefs.gpsTaggingEnabled(this)
- serviceScope.launch {
- AppDatabase.getInstance(this@ScanForegroundService).detectionDao().insert(
- DetectionEntity(
- mac = "CELL " + a.key.substringAfter(':'), label = a.title, source = "CELL", rssi = 0,
- timestamp = now,
- latitude = if (tag) loc?.latitude else null, longitude = if (tag) loc?.longitude else null,
- category = Category.CELL_ANOMALY.name, confidence = a.confidence, evidence = a.detail
- )
- )
- }
+ logDetection("CELL " + a.key.substringAfter(':'), "CELL", hit, now, loc?.latitude, loc?.longitude)
if (a.confidence >= Prefs.alertThreshold(this, hit.category)) {
val off = alertsOff(hit.category)
NotificationHelper.sendMapAlert(this, "cell:" + a.key, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java, banner = AlertKind.BANNER !in off)
diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
index b1e9462..8e2e91b 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -7,12 +7,19 @@ import android.provider.Settings
import android.view.View
import android.widget.RadioButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import android.widget.LinearLayout
+import android.widget.TextView
+import android.widget.AdapterView
+import android.widget.ArrayAdapter
import com.rfsentinel.app.ui.CustomThemes
import com.rfsentinel.app.ui.ThemeManager
import com.rfsentinel.app.ui.ThemeImport
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
+import androidx.core.widget.doAfterTextChanged
+import androidx.appcompat.widget.AppCompatSpinner
+import com.google.android.material.slider.Slider
import com.google.android.material.switchmaterial.SwitchMaterial
import com.rfsentinel.app.R
import com.rfsentinel.app.data.AppDatabase
@@ -66,6 +73,9 @@ class SettingsActivity : AppCompatActivity() {
* (possibly twice: ours + AppCompat's night-mode switch).
*/
private var resumeScroll: Int? = null
+ private val SCAN_MODES = intArrayOf(
+ ScanSettings.SCAN_MODE_LOW_LATENCY, ScanSettings.SCAN_MODE_BALANCED, ScanSettings.SCAN_MODE_LOW_POWER
+ )
}
private lateinit var binding: ActivitySettingsBinding
private var stopObservingPrefetch: (() -> Unit)? = null
@@ -85,6 +95,50 @@ class SettingsActivity : AppCompatActivity() {
private var aircraftStatusText: android.widget.TextView? = null
private var wazeStatusText: android.widget.TextView? = null
+ private fun SwitchMaterial.bindLive(on: Boolean, save: (Boolean) -> Unit) {
+ isChecked = on
+ setOnCheckedChangeListener { _, value -> save(value) }
+ }
+
+ private fun LinearLayout.toggle(text: String, on: Boolean, details: String? = null, save: (Boolean) -> Unit) =
+ SwitchMaterial(this@SettingsActivity).apply {
+ this.text = text
+ bindLive(on, save)
+ }.also { addView(if (details == null) it else infoRow(it, details)) }
+
+ private fun LinearLayout.label(text: String, small: Boolean = false) = TextView(this@SettingsActivity).apply {
+ this.text = text
+ textSize = if (small) 12f else 14f
+ if (small) alpha = 0.75f
+ setPadding(0, if (small) 0 else dp(10), 0, dp(2))
+ }.also { addView(it) }
+
+ private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt()
+
+ private fun spinner(labels: List<String>, selected: Int, description: String, save: (Int) -> Unit) =
+ AppCompatSpinner(this).apply {
+ adapter = ArrayAdapter(this@SettingsActivity, android.R.layout.simple_spinner_item, labels).also {
+ it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
+ }
+ setSelection(selected)
+ contentDescription = description
+ onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
+ override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) = save(position)
+ override fun onNothingSelected(parent: AdapterView<*>?) {}
+ }
+ }
+
+ private fun slider(from: Int, to: Int, current: Int, step: Int = 1, description: String,
+ format: ((Int) -> String)? = null, save: (Int) -> Unit) = Slider(this).apply {
+ valueFrom = from.toFloat()
+ valueTo = to.toFloat()
+ stepSize = step.toFloat()
+ value = current.coerceIn(from, to).toFloat()
+ contentDescription = description
+ if (format != null) setLabelFormatter { format(it.toInt()) }
+ addOnChangeListener { _, value, fromUser -> if (fromUser) save(value.toInt()) }
+ }
+
private val bannerPicker = registerForActivityResult(
androidx.activity.result.contract.ActivityResultContracts.GetContent()
) { uri ->
@@ -245,6 +299,12 @@ class SettingsActivity : AppCompatActivity() {
binding.ignoredCamerasButton.shownIf(n > 0)
}
+ private fun presetSwitches() = mapOf(
+ "global" to binding.presetGlobal, "canada" to binding.presetCanada, "us" to binding.presetUs,
+ "france" to binding.presetFrance, "uk" to binding.presetUk, "portugal" to binding.presetPortugal,
+ "germany" to binding.presetGermany, "spain" to binding.presetSpain, "italy" to binding.presetItaly
+ )
+
/** ESP32 boards on USB (OUI-Spy / GhostESP / Marauder) and an OUI-SPY board over Bluetooth. */
/** Speed, voice and a test button for spoken alerts; changes apply right away. */
private fun setupVoiceControls() {
@@ -268,8 +328,7 @@ class SettingsActivity : AppCompatActivity() {
com.rfsentinel.app.util.AlertPlayer.testVoice(this@SettingsActivity, binding.shortVoiceSwitch.isChecked)
}
})
- binding.voicePauseMusicSwitch.isChecked = Prefs.voicePausesMusic(this)
- binding.voicePauseMusicSwitch.setOnCheckedChangeListener { _, on -> Prefs.setVoicePausesMusic(this, on) }
+ binding.voicePauseMusicSwitch.bindLive(Prefs.voicePausesMusic(this)) { Prefs.setVoicePausesMusic(this, it) }
// Tests what is on screen (Settings save when you leave), so the short switch counts right away.
binding.voiceTestButton.setOnClickListener {
com.rfsentinel.app.util.AlertPlayer.testVoice(this, binding.shortVoiceSwitch.isChecked)
@@ -1095,14 +1154,14 @@ class SettingsActivity : AppCompatActivity() {
/** Settings the search hid for not matching (shown again when it changes or is cleared). */
private val searchHidden = mutableListOf<View>()
- /**
- * Shows or hides a setting for the app's own reasons (a switch turned off, nothing to say...). It
- * also takes the setting off the search's list, so clearing the search leaves it the way this set it.
- */
/** Radio buttons listed in the order of the choices they stand for. */
private fun android.widget.RadioGroup.checkIndex(i: Int) = check(getChildAt(i).id)
private val android.widget.RadioGroup.checkedIndex get() = indexOfChild(findViewById(checkedRadioButtonId))
+ /**
+ * Shows or hides a setting for the app's own reasons (a switch turned off, nothing to say...). It
+ * also takes the setting off the search's list, so clearing the search leaves it the way this set it.
+ */
private fun View.shownIf(on: Boolean) {
setTag(R.id.search_hidden, null)
visibility = if (on) View.VISIBLE else View.GONE
@@ -1135,15 +1194,11 @@ class SettingsActivity : AppCompatActivity() {
getSystemService(android.view.inputmethod.InputMethodManager::class.java)?.hideSoftInputFromWindow(v.windowToken, 0)
true
}
- searchInput.addTextChangedListener(object : android.text.TextWatcher {
- override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
- override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
- override fun afterTextChanged(s: android.text.Editable?) {
- val q = s?.toString().orEmpty()
- clear.visibility = if (q.isEmpty()) View.GONE else View.VISIBLE
- filterSettings(q)
- }
- })
+ searchInput.doAfterTextChanged {
+ val q = it?.toString().orEmpty()
+ clear.visibility = if (q.isEmpty()) View.GONE else View.VISIBLE
+ filterSettings(q)
+ }
return android.widget.LinearLayout(this).apply {
orientation = android.widget.LinearLayout.HORIZONTAL
gravity = android.view.Gravity.CENTER_VERTICAL
@@ -1370,43 +1425,27 @@ class SettingsActivity : AppCompatActivity() {
/** Settings > RTL-SDR radio, built in code; everything is saved as you change it. */
private fun setupRadioSection() {
val box = binding.sectionRadio
- val dp = resources.displayMetrics.density
- fun label(t: String, small: Boolean = false) = android.widget.TextView(this).apply {
- text = t; textSize = if (small) 12f else 14f
- if (small) alpha = 0.75f
- setPadding(0, (if (small) 0 else 10 * dp).toInt(), 0, (2 * dp).toInt())
- }.also { box.addView(it) }
fun slider(from: Int, to: Int, value: Int, text: (Int) -> String, save: (Int) -> Unit) {
- val l = label(text(value))
- box.addView(com.google.android.material.slider.Slider(this).apply {
- valueFrom = from.toFloat(); valueTo = to.toFloat(); stepSize = 1f
- this.value = value.coerceIn(from, to).toFloat()
- contentDescription = text(value)
- addOnChangeListener { _, v, fromUser -> if (fromUser) { save(v.toInt()); l.text = text(v.toInt()) } }
+ val l = box.label(text(value))
+ box.addView([email protected](from, to, value, description = text(value)) {
+ save(it)
+ l.text = text(it)
})
}
fun lines(title: String, hint: String, value: String, details: String? = null, save: (String) -> Unit) {
- label(title).also { if (details != null) info(it, details) }
+ box.label(title).also { if (details != null) info(it, details) }
box.addView(android.widget.EditText(this).apply {
setText(value); this.hint = hint
minLines = 2; maxLines = 8; gravity = android.view.Gravity.TOP
inputType = android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_FLAG_MULTI_LINE
importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_NO
- addTextChangedListener(object : android.text.TextWatcher {
- override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
- override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
- override fun afterTextChanged(s: android.text.Editable?) { save(s?.toString().orEmpty()) }
- })
+ doAfterTextChanged { save(it?.toString().orEmpty()) }
})
}
- fun switch(t: String, on: Boolean, info: String? = null, save: (Boolean) -> Unit) = SwitchMaterial(this).apply {
- text = t; isChecked = on
- setOnCheckedChangeListener { _, v -> save(v) }
- }.also { box.addView(if (info == null) it else infoRow(it, info)) }
// What the SDR does: any mix; with more than one ticked it takes turns.
var showSdrOptions: () -> Unit = {}
- info(label("Scan with the SDR"), "Tick what the RTL-SDR or HackRF does while scanning. One SDR hears one thing at a time: " +
+ info(box.label("Scan with the SDR"), "Tick what the RTL-SDR or HackRF does while scanning. One SDR hears one thing at a time: " +
"with more than one ticked it takes turns, and each scan hears nothing while another has its turn. " +
"Tick only one to give it all the time.", "Scan with the SDR")
fun scan(t: String, on: Boolean, details: String, save: (Boolean) -> Unit) = android.widget.CheckBox(this).apply {
@@ -1482,7 +1521,7 @@ class SettingsActivity : AppCompatActivity() {
info(box.getChildAt(box.childCount - 2), "A radio is reported once its signal is this far above the noise. Lower hears farther, with more false alarms. " +
"Below about 10 dB the noise's own flicker sets off some alerts: good for testing how far a known radio carries " +
"(a fire station's TETRA, say), noisy for everyday use.", "Sensitivity")
- label("Bands to sweep")
+ box.label("Bands to sweep")
val off = Prefs.radioBandsOff(this).toMutableSet()
for ((key, band) in com.rfsentinel.app.sdr.RadioSettings.BUILT_IN) {
box.addView(android.widget.CheckBox(this).apply {
@@ -1498,12 +1537,12 @@ class SettingsActivity : AppCompatActivity() {
lines("Never report these ranges", "462-469 business band\n151.8-152.0", Prefs.radioExcluded(this), "One per line, in MHz.") { Prefs.setRadioExcluded(this, it) }
lines("Watch these frequencies", "154.4300 County fire dispatch\n460.125", Prefs.radioTargets(this),
"Always reported when active, whatever the sensitivity. One per line, in MHz, with an optional name.") { Prefs.setRadioTargets(this, it) }
- switch("Say the frequency", Prefs.radioSpeakFreq(this), "Says the frequency (and its name) instead of \"Radio transmitting nearby\".") { Prefs.setRadioSpeakFreq(this, it) }
- switch("Detect cellular transmitters", Prefs.radioCellOn(this),
+ box.toggle("Say the frequency", Prefs.radioSpeakFreq(this), "Says the frequency (and its name) instead of \"Radio transmitting nearby\".") { Prefs.setRadioSpeakFreq(this, it) }
+ box.toggle("Detect cellular transmitters", Prefs.radioCellOn(this),
"Experimental. Watches the phone / modem side of the LTE bands (uplink) for a transmitter travelling near you: a vehicle modem, a " +
"Cradlepoint-style router, a camera with a SIM. Energy only, nothing decoded. Adds time to each sweep; " +
"a phone counts too, so it is a weak sign on its own.") { Prefs.setRadioCellOn(this, it) }
- switch("Detect TETRA radios", Prefs.radioTetraOn(this),
+ box.toggle("Detect TETRA radios", Prefs.radioTetraOn(this),
"Watches 380-385 MHz, where emergency-service TETRA handsets transmit in Europe and many other countries. " +
"A handset sends short time-slot bursts; that rhythm marks it as a TETRA radio. Energy only: TETRA is encrypted " +
"and nothing is decoded. On by default when the phone's region is in Europe.") { Prefs.setRadioTetraOn(this, it) }
@@ -1514,8 +1553,8 @@ class SettingsActivity : AppCompatActivity() {
sweepViews = (sweepFrom until box.childCount).map(box::getChildAt)
showSdrOptions()
- label("Frequency names")
- freqListText = label("", small = true)
+ box.label("Frequency names")
+ freqListText = box.label("", small = true)
com.rfsentinel.app.sdr.FreqNames.load(this)
updateFreqListText()
box.addView(android.widget.LinearLayout(this).apply {
@@ -1532,7 +1571,7 @@ class SettingsActivity : AppCompatActivity() {
})
})
- val rrSwitch = switch("Name hits from RadioReference", Prefs.radioReferenceOn(this),
+ val rrSwitch = box.toggle("Name hits from RadioReference", Prefs.radioReferenceOn(this),
"Names a hit from RadioReference's database. Needs your own RadioReference Premium login and developer key, stored encrypted on this phone.") {
Prefs.setRadioReferenceOn(this, it)
}
@@ -1553,7 +1592,7 @@ class SettingsActivity : AppCompatActivity() {
secret("RadioReference username (not your email)", com.rfsentinel.app.sdr.RadioReference.USER_KEY, false)
secret("RadioReference password", com.rfsentinel.app.sdr.RadioReference.PASS_KEY, true)
secret("RadioReference developer key", com.rfsentinel.app.sdr.RadioReference.APPKEY_KEY, true)
- val rrStatus = label(com.rfsentinel.app.sdr.RadioReference.status.ifEmpty { "Stored encrypted on this phone." }, small = true)
+ val rrStatus = box.label(com.rfsentinel.app.sdr.RadioReference.status.ifEmpty { "Stored encrypted on this phone." }, small = true)
box.addView(com.google.android.material.button.MaterialButton(this, null, android.R.attr.borderlessButtonStyle).apply {
text = "Test login"
setOnClickListener {
@@ -1622,36 +1661,26 @@ class SettingsActivity : AppCompatActivity() {
/** Settings > Navigation: directions, route preferences, distance units and the places kept for it. */
private fun setupNavSection() {
val box = binding.sectionNav
- val dp = resources.displayMetrics.density
- fun label(t: String, small: Boolean = false) = android.widget.TextView(this).apply {
- text = t; textSize = if (small) 12f else 14f
- if (small) alpha = 0.75f
- setPadding(0, (if (small) 0 else 10 * dp).toInt(), 0, (2 * dp).toInt())
- }.also { box.addView(it) }
- fun switch(t: String, on: Boolean, info: String? = null, save: (Boolean) -> Unit) = SwitchMaterial(this).apply {
- text = t; isChecked = on
- setOnCheckedChangeListener { _, v -> save(v) }
- }.also { box.addView(if (info == null) it else infoRow(it, info)) }
- switch("Spoken directions", Prefs.navVoice(this), "Turn-by-turn directions spoken aloud. Muting them never mutes the detection alerts.") { Prefs.setNavVoice(this, it) }
- switch("Scan when a route starts", Prefs.navStartScan(this),
+ box.toggle("Spoken directions", Prefs.navVoice(this), "Turn-by-turn directions spoken aloud. Muting them never mutes the detection alerts.") { Prefs.setNavVoice(this, it) }
+ box.toggle("Scan when a route starts", Prefs.navStartScan(this),
"Starts scanning when you start a destination. A scan already running is left alone, and the scan keeps going after you arrive.") { Prefs.setNavStartScan(this, it) }
- switch("Keep the screen on while guiding", Prefs.navKeepScreenOn(this)) { Prefs.setNavKeepScreenOn(this, it) }
- switch("Night map after sunset", Prefs.navAutoNight(this),
+ box.toggle("Keep the screen on while guiding", Prefs.navKeepScreenOn(this)) { Prefs.setNavKeepScreenOn(this, it) }
+ box.toggle("Night map after sunset", Prefs.navAutoNight(this),
"While guiding, the map turns dark after sunset, worked out on the phone from your position and the time. " +
"Pressing the sun / moon button on the map keeps the look you chose instead.") { Prefs.setNavAutoNight(this, it) }
- box.addView(infoRow(label("Routes avoid").also { box.removeView(it) },
+ box.addView(infoRow(box.label("Routes avoid").also { box.removeView(it) },
"Ticking one while you plan a route is remembered here for the next one.\n\n" +
"Speed cameras and plate readers: routes go round the cameras of the camera map (Known cameras) where there is a way round, " +
"and each route says what is left on it. The cameras along the route are fetched first if they are not on the phone. " +
"A camera right at the start or end, or on the only bridge, can't be avoided. A detour can be longer."))
- switch("Tolls", Prefs.navAvoidTolls(this)) { Prefs.setNavAvoidTolls(this, it) }
- switch("Highways", Prefs.navAvoidHighways(this)) { Prefs.setNavAvoidHighways(this, it) }
- switch("Ferries", Prefs.navAvoidFerries(this)) { Prefs.setNavAvoidFerries(this, it) }
- switch("Speed cameras", Prefs.navAvoidSpeedCameras(this)) { Prefs.setNavAvoidSpeedCameras(this, it) }
- switch("Plate readers", Prefs.navAvoidPlateReaders(this)) { Prefs.setNavAvoidPlateReaders(this, it) }
+ box.toggle("Tolls", Prefs.navAvoidTolls(this)) { Prefs.setNavAvoidTolls(this, it) }
+ box.toggle("Highways", Prefs.navAvoidHighways(this)) { Prefs.setNavAvoidHighways(this, it) }
+ box.toggle("Ferries", Prefs.navAvoidFerries(this)) { Prefs.setNavAvoidFerries(this, it) }
+ box.toggle("Speed cameras", Prefs.navAvoidSpeedCameras(this)) { Prefs.setNavAvoidSpeedCameras(this, it) }
+ box.toggle("Plate readers", Prefs.navAvoidPlateReaders(this)) { Prefs.setNavAvoidPlateReaders(this, it) }
- label("Places")
+ box.label("Places")
val places = android.widget.TextView(this).apply { textSize = 14f; alpha = 0.8f }
fun showPlaces() {
places.text = "Home: ${Prefs.navHome(this@SettingsActivity)?.name ?: "not set"}\n" +
@@ -1819,8 +1848,7 @@ class SettingsActivity : AppCompatActivity() {
Prefs.setMapSpeedLimitLive(this, on)
if (!on) com.rfsentinel.app.nav.SpeedLimits.Live.reset()
}
- binding.mapTowersSwitch.isChecked = Prefs.showCellTowers(this)
- binding.mapTowersSwitch.setOnCheckedChangeListener { _, on -> Prefs.setShowCellTowers(this, on) }
+ binding.mapTowersSwitch.bindLive(Prefs.showCellTowers(this)) { Prefs.setShowCellTowers(this, it) }
binding.mapCctvSwitch.isChecked = Prefs.showCctv(this)
binding.mapCctvPrivateSwitch.isChecked = Prefs.cctvPrivate(this)
binding.mapCctvPrivateSwitch.isEnabled = binding.mapCctvSwitch.isChecked
@@ -1917,15 +1945,6 @@ class SettingsActivity : AppCompatActivity() {
}
}
- /** A small grey line under a category switch, indented like the AirTag option. */
- private fun indentedNote(text: String) = android.widget.TextView(this).apply {
- this.text = text
- textSize = 12f
- alpha = 0.75f
- setPadding((24 * resources.displayMetrics.density).toInt(), 0, 0, (6 * resources.displayMetrics.density).toInt())
- shownIf(text.isNotBlank())
- }
-
private fun showNote(view: android.widget.TextView?, text: String) {
view ?: return
view.text = text
@@ -2148,22 +2167,6 @@ class SettingsActivity : AppCompatActivity() {
val backendGroup = android.widget.RadioGroup(this).apply { addView(ninjaBtn); addView(directBtn) }
box.addView(backendGroup)
// Two independent ranges (both backends): how close a report must be to alert, and how far the map shows them.
- fun rangeSlider(label: String, from: Float, to: Float, km: Int, desc: String, save: (Int) -> Unit) {
- val text = android.widget.TextView(this).apply { textSize = 12f; alpha = 0.75f }
- fun show(v: Int) { text.text = "$label ${com.rfsentinel.app.util.Units.km(v)}" }
- show(km)
- box.addView(text)
- box.addView(com.google.android.material.slider.Slider(this).apply {
- valueFrom = from; valueTo = to; stepSize = 1f
- value = km.toFloat().coerceIn(from, to)
- contentDescription = desc
- setLabelFormatter { com.rfsentinel.app.util.Units.km(it.toInt()) }
- addOnChangeListener { _, v, fromUser ->
- if (!fromUser) return@addOnChangeListener
- save(v.toInt()); show(v.toInt())
- }
- })
- }
// The alert range steps through fixed distances, from 100 m up.
val steps = Prefs.WAZE_ALERT_STEPS_M
val alertText = android.widget.TextView(this).apply { textSize = 12f; alpha = 0.75f }
@@ -2171,18 +2174,20 @@ class SettingsActivity : AppCompatActivity() {
val alertNow = Prefs.wazeAlertM(this)
showAlert(alertNow)
box.addView(alertText)
- box.addView(com.google.android.material.slider.Slider(this).apply {
- valueFrom = 0f; valueTo = (steps.size - 1).toFloat(); stepSize = 1f
- value = steps.indexOf(alertNow).coerceAtLeast(0).toFloat()
- contentDescription = "Waze alert distance"
- setLabelFormatter { Prefs.formatRange(steps[it.toInt().coerceIn(0, steps.size - 1)]) }
- addOnChangeListener { _, v, fromUser ->
- if (!fromUser) return@addOnChangeListener
- val m = steps[v.toInt().coerceIn(0, steps.size - 1)]
- Prefs.setWazeAlertM(this@SettingsActivity, m); showAlert(m)
- }
+ box.addView(slider(0, steps.lastIndex, steps.indexOf(alertNow).coerceAtLeast(0), description = "Waze alert distance",
+ format = { Prefs.formatRange(steps[it]) }) {
+ Prefs.setWazeAlertM(this, steps[it])
+ showAlert(steps[it])
+ })
+ val viewText = TextView(this).apply { textSize = 12f; alpha = 0.75f }
+ fun showView(km: Int) { viewText.text = "Show reports on the map within ${com.rfsentinel.app.util.Units.km(km)}" }
+ showView(Prefs.wazeViewKm(this))
+ box.addView(viewText)
+ box.addView(slider(1, 20, Prefs.wazeViewKm(this), description = "Waze map view range in kilometres",
+ format = { com.rfsentinel.app.util.Units.km(it) }) {
+ Prefs.setWazeViewKm(this, it)
+ showView(it)
})
- rangeSlider("Show reports on the map within", 1f, 20f, Prefs.wazeViewKm(this), "Waze map view range in kilometres") { Prefs.setWazeViewKm(this, it) }
// How often Waze is asked. Each backend has its own steps; only the chosen backend's slider shows.
fun intervalBlock(direct: Boolean): android.widget.LinearLayout {
val steps = if (direct) Prefs.WAZE_DIRECT_INTERVALS_S else Prefs.WAZE_NINJA_INTERVALS_S
@@ -2202,16 +2207,10 @@ class SettingsActivity : AppCompatActivity() {
val now = Prefs.wazeIntervalS(this, direct)
show(now)
col.addView(text)
- col.addView(com.google.android.material.slider.Slider(this).apply {
- valueFrom = 0f; valueTo = (steps.size - 1).toFloat(); stepSize = 1f
- value = steps.indexOf(now).coerceAtLeast(0).toFloat()
- contentDescription = "How often to check Waze"
- setLabelFormatter { Prefs.formatInterval(steps[it.toInt().coerceIn(0, steps.size - 1)]) }
- addOnChangeListener { _, v, fromUser ->
- if (!fromUser) return@addOnChangeListener
- val sec = steps[v.toInt().coerceIn(0, steps.size - 1)]
- Prefs.setWazeIntervalS(this@SettingsActivity, direct, sec); show(sec)
- }
+ col.addView(slider(0, steps.lastIndex, steps.indexOf(now).coerceAtLeast(0), description = "How often to check Waze",
+ format = { Prefs.formatInterval(steps[it]) }) {
+ Prefs.setWazeIntervalS(this, direct, steps[it])
+ show(steps[it])
})
col.addView(hint)
return col
@@ -2221,31 +2220,20 @@ class SettingsActivity : AppCompatActivity() {
box.addView(directInterval)
box.addView(ninjaInterval)
// Behaviour switches: each has a line under it saying what it does.
- fun switchRow(label: String, hint: String, checked: Boolean, save: (Boolean) -> Unit) {
- box.addView(infoRow(SwitchMaterial(this).apply {
- text = label
- isChecked = checked
- setOnCheckedChangeListener { _, on -> save(on) }
- }, hint))
- }
- switchRow("Slower when parked, faster on fast roads",
- "Parked for 90 s: checks run 4 times less often. Over 80 km/h: twice as often (Waze direct only).",
- Prefs.wazeAdaptive(this)) { Prefs.setWazeAdaptive(this, it) }
- switchRow("Only alert for reports ahead of me",
+ box.toggle("Slower when parked, faster on fast roads", Prefs.wazeAdaptive(this),
+ "Parked for 90 s: checks run 4 times less often. Over 80 km/h: twice as often (Waze direct only).") { Prefs.setWazeAdaptive(this, it) }
+ box.toggle("Only alert for reports ahead of me", Prefs.wazeAheadOnly(this),
"While you drive, only reports on the road you're on, ahead of you, alert, flash or speak - checked on the map's " +
"roads, so one on a parallel road, a cross street, an overpass or behind you stays quiet (it stays on the list, " +
"marked \"not on your way\" unless you hide them below). While you are being guided to a destination the route " +
"decides: only reports on the part of it still ahead count, round corners too. Where the map can't tell yet, " +
"reports behind you stay quiet. Parked, or before you've driven off, there is no \"ahead\" yet, so reports " +
- "stay quiet until you move.",
- Prefs.wazeAheadOnly(this)) { Prefs.setWazeAheadOnly(this, it) }
- switchRow("Hide reports that aren't on my way",
+ "stay quiet until you move.") { Prefs.setWazeAheadOnly(this, it) }
+ box.toggle("Hide reports that aren't on my way", Prefs.wazeHideOffWay(this),
"With the switch above on, a report behind you, on another street or off your route is left off the list (the map " +
- "still shows it). Off: it stays listed, quiet, marked \"not on your way\".",
- Prefs.wazeHideOffWay(this)) { Prefs.setWazeHideOffWay(this, it) }
- switchRow("Call out again as I get closer",
- "Speaks at 1 km, 500 m and 200 m when voice alerts are on, or in the car.",
- Prefs.wazeApproach(this)) { Prefs.setWazeApproach(this, it) }
+ "still shows it). Off: it stays listed, quiet, marked \"not on your way\".") { Prefs.setWazeHideOffWay(this, it) }
+ box.toggle("Call out again as I get closer", Prefs.wazeApproach(this),
+ "Speaks at 1 km, 500 m and 200 m when voice alerts are on, or in the car.") { Prefs.setWazeApproach(this, it) }
// What to watch (ticked) and what an alert of that kind does (the menu beside it).
box.addView(android.widget.TextView(this).apply { text = "What to alert on, and how loud"; textSize = 12f; alpha = 0.75f })
val levels = com.rfsentinel.app.online.WazePolice.Level.entries
@@ -2265,18 +2253,8 @@ class SettingsActivity : AppCompatActivity() {
Prefs.setWazeTypes(this@SettingsActivity, now)
}
})
- row.addView(androidx.appcompat.widget.AppCompatSpinner(this).apply {
- adapter = android.widget.ArrayAdapter(this@SettingsActivity, android.R.layout.simple_spinner_item, levels.map { it.label }).also {
- it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
- }
- setSelection(Prefs.wazeLevel(this@SettingsActivity, t).ordinal)
- contentDescription = "What a ${t.label.lowercase()} alert does"
- onItemSelectedListener = object : android.widget.AdapterView.OnItemSelectedListener {
- override fun onItemSelected(parent: android.widget.AdapterView<*>?, view: View?, position: Int, id: Long) {
- Prefs.setWazeLevel(this@SettingsActivity, t, levels[position])
- }
- override fun onNothingSelected(parent: android.widget.AdapterView<*>?) {}
- }
+ row.addView(spinner(levels.map { it.label }, Prefs.wazeLevel(this, t).ordinal, "What a ${t.label.lowercase()} alert does") {
+ Prefs.setWazeLevel(this, t, levels[it])
})
box.addView(row)
}
@@ -2363,35 +2341,26 @@ class SettingsActivity : AppCompatActivity() {
binding.themeGroup.removeAllViews()
val current = ThemeManager.current(this)
val custom = ThemeManager.custom(this)
- ThemeManager.builtIn.forEach { t ->
- val unavailable = t == ThemeManager.AppTheme.MATERIAL_YOU && !ThemeManager.isDynamicColorAvailable
- binding.themeGroup.addView(RadioButton(this).apply {
- id = View.generateViewId()
- text = t.title
- isChecked = t == current
- setOnCheckedChangeListener { _, checked ->
- if (checked && t != ThemeManager.current(this@SettingsActivity)) {
- resumeScroll = binding.root.scrollY
- ThemeManager.set(this@SettingsActivity, t)
- recreate()
- }
+ fun choice(title: String, checked: Boolean, selected: () -> Boolean, choose: () -> Unit) = RadioButton(this).apply {
+ id = View.generateViewId()
+ text = title
+ isChecked = checked
+ setOnCheckedChangeListener { _, checked ->
+ if (checked && !selected()) {
+ resumeScroll = binding.root.scrollY
+ choose()
+ recreate()
}
- })
+ }
+ }.also { binding.themeGroup.addView(it) }
+ ThemeManager.builtIn.forEach { theme ->
+ choice(theme.title, theme == current, { theme == ThemeManager.current(this) }) { ThemeManager.set(this, theme) }
}
- CustomThemes.all(this).forEach { c ->
- binding.themeGroup.addView(RadioButton(this).apply {
- id = View.generateViewId()
- text = c.name
- isChecked = current == ThemeManager.AppTheme.CUSTOM && custom?.id == c.id
- setOnCheckedChangeListener { _, checked ->
- if (checked && !(ThemeManager.current(this@SettingsActivity) == ThemeManager.AppTheme.CUSTOM && ThemeManager.custom(this@SettingsActivity)?.id == c.id)) {
- resumeScroll = binding.root.scrollY
- ThemeManager.setCustom(this@SettingsActivity, c.id)
- recreate()
- }
- }
- setOnLongClickListener { editTheme(c.id); true }
- })
+ CustomThemes.all(this).forEach { theme ->
+ choice(theme.name, current == ThemeManager.AppTheme.CUSTOM && custom?.id == theme.id,
+ { ThemeManager.current(this) == ThemeManager.AppTheme.CUSTOM && ThemeManager.custom(this)?.id == theme.id }) {
+ ThemeManager.setCustom(this, theme.id)
+ }.setOnLongClickListener { editTheme(theme.id); true }
}
}
@@ -2505,18 +2474,8 @@ class SettingsActivity : AppCompatActivity() {
// Scanning
binding.bleSwitch.isChecked = Prefs.bleEnabled(this)
binding.wifiSwitch.isChecked = Prefs.wifiEnabled(this)
- binding.wifiBandGroup.check(when (Prefs.wifiBand(this)) {
- Prefs.WifiBand.LOW -> R.id.wifiBandLow
- Prefs.WifiBand.HIGH -> R.id.wifiBandHigh
- Prefs.WifiBand.ALL -> R.id.wifiBandAll
- })
- binding.scanModeGroup.check(
- when (Prefs.bleScanMode(this)) {
- ScanSettings.SCAN_MODE_BALANCED -> R.id.scanModeBalanced
- ScanSettings.SCAN_MODE_LOW_POWER -> R.id.scanModeLowPower
- else -> R.id.scanModeLowLatency
- }
- )
+ binding.wifiBandGroup.checkIndex(Prefs.wifiBand(this).ordinal)
+ binding.scanModeGroup.checkIndex(SCAN_MODES.indexOf(Prefs.bleScanMode(this)).coerceAtLeast(0))
binding.intervalInput.setText((Prefs.scanIntervalMs(this) / 1000).toString())
binding.wifiThrottleButton.setOnClickListener { openWifiThrottleSetting() }
binding.disable2gButton.setOnClickListener {
@@ -2593,27 +2552,20 @@ class SettingsActivity : AppCompatActivity() {
if (c == Category.POLICE_REPORT) addWazeControls(sw)
}
val enabledPresets = OuiWatchlist.getEnabledPresets(this)
- binding.presetGlobal.isChecked = "global" in enabledPresets
- binding.presetCanada.isChecked = "canada" in enabledPresets
- binding.presetUs.isChecked = "us" in enabledPresets
- binding.presetFrance.isChecked = "france" in enabledPresets
- binding.presetFrance.setOnCheckedChangeListener { _, on -> if (on) com.rfsentinel.app.ui.RegionNotice.show(this, "france") }
- binding.presetUk.isChecked = "uk" in enabledPresets
- binding.presetPortugal.isChecked = "portugal" in enabledPresets
- binding.presetGermany.isChecked = "germany" in enabledPresets
- binding.presetGermany.setOnCheckedChangeListener { _, on -> if (on) com.rfsentinel.app.ui.RegionNotice.show(this, "germany") }
- binding.presetSpain.isChecked = "spain" in enabledPresets
- binding.presetItaly.isChecked = "italy" in enabledPresets
+ presetSwitches().forEach { (key, control) ->
+ control.isChecked = key in enabledPresets
+ if (key == "france" || key == "germany") control.setOnCheckedChangeListener { _, on ->
+ if (on) com.rfsentinel.app.ui.RegionNotice.show(this, key)
+ }
+ }
// Alerts
val threshold = Prefs.alertThreshold(this)
- binding.thresholdGroup.check(
- when {
- threshold >= 80 -> R.id.thresholdStrong
- threshold >= 50 -> R.id.thresholdMedium
- else -> R.id.thresholdWeak
- }
- )
+ binding.thresholdGroup.checkIndex(when {
+ threshold >= 80 -> 2
+ threshold >= 50 -> 1
+ else -> 0
+ })
binding.soundSwitch.isChecked = Prefs.soundEnabled(this)
binding.alertVolumeGroup.checkIndex(Prefs.alertVolume(this).ordinal)
// Each choice plays the alert sound at that volume.
@@ -2647,11 +2599,9 @@ class SettingsActivity : AppCompatActivity() {
binding.shortVoiceSwitch.isChecked = Prefs.shortVoice(this)
setupVoiceControls()
binding.discreetSwitch.isChecked = Prefs.discreetMode(this)
- val rotations = mapOf(R.id.rotationNormal to Prefs.Rotation.NORMAL, R.id.rotationAllWays to Prefs.Rotation.ALL_WAYS,
- R.id.rotationUpsideDown to Prefs.Rotation.UPSIDE_DOWN)
- binding.rotationGroup.check(rotations.entries.first { it.value == Prefs.rotation(this) }.key)
- binding.rotationGroup.setOnCheckedChangeListener { _, id ->
- rotations[id]?.let { Prefs.setRotation(this, it) }
+ binding.rotationGroup.checkIndex(Prefs.rotation(this).ordinal)
+ binding.rotationGroup.setOnCheckedChangeListener { group, _ ->
+ Prefs.Rotation.entries.getOrNull(group.checkedIndex)?.let { Prefs.setRotation(this, it) }
(application as com.rfsentinel.app.RFSentinelApp).applyOrientation(this) // turns right away
}
binding.floatingMapSwitch.isChecked = Prefs.floatingMap(this) && Settings.canDrawOverlays(this)
@@ -2725,11 +2675,7 @@ class SettingsActivity : AppCompatActivity() {
binding.traceEveryPingSwitch.isChecked = Prefs.traceEveryPing(this)
binding.ouiSpyRelaySwitch.isChecked = Prefs.ouiSpyRelayAll(this)
binding.ouiSpyPhoneBleSwitch.isChecked = Prefs.ouiSpyPhoneBle(this)
- binding.screenModeGroup.check(when (Prefs.screenMode(this)) {
- Prefs.ScreenMode.ALWAYS_ON -> R.id.screenAlwaysOn
- Prefs.ScreenMode.ON_WHILE_CHARGING -> R.id.screenOnCharging
- Prefs.ScreenMode.NORMAL -> R.id.screenNormal
- })
+ binding.screenModeGroup.checkIndex(Prefs.screenMode(this).ordinal)
binding.knownAlprSwitch.isChecked = Prefs.knownAlprAlerts(this)
binding.cellChangeSwitch.isChecked = Prefs.cellChangeAlerts(this)
binding.speedCameraSwitch.isChecked = Prefs.speedCameraAlerts(this)
@@ -2936,19 +2882,8 @@ class SettingsActivity : AppCompatActivity() {
private fun save() {
Prefs.setBleEnabled(this, binding.bleSwitch.isChecked)
Prefs.setWifiEnabled(this, binding.wifiSwitch.isChecked)
- Prefs.setWifiBand(this, when (binding.wifiBandGroup.checkedRadioButtonId) {
- R.id.wifiBandLow -> Prefs.WifiBand.LOW
- R.id.wifiBandHigh -> Prefs.WifiBand.HIGH
- else -> Prefs.WifiBand.ALL
- })
- Prefs.setBleScanMode(
- this,
- when (binding.scanModeGroup.checkedRadioButtonId) {
- R.id.scanModeBalanced -> ScanSettings.SCAN_MODE_BALANCED
- R.id.scanModeLowPower -> ScanSettings.SCAN_MODE_LOW_POWER
- else -> ScanSettings.SCAN_MODE_LOW_LATENCY
- }
- )
+ Prefs.setWifiBand(this, Prefs.WifiBand.entries.getOrElse(binding.wifiBandGroup.checkedIndex) { Prefs.WifiBand.ALL })
+ Prefs.setBleScanMode(this, SCAN_MODES.getOrElse(binding.scanModeGroup.checkedIndex) { ScanSettings.SCAN_MODE_LOW_LATENCY })
val intervalSec = binding.intervalInput.text.toString().toLongOrNull() ?: 30L
Prefs.setScanIntervalMs(this, intervalSec.coerceAtLeast(5) * 1000L)
Prefs.setAutoStartOnBoot(this, binding.bootSwitch.isChecked)
@@ -2963,26 +2898,9 @@ class SettingsActivity : AppCompatActivity() {
val name = com.rfsentinel.app.online.OnlineWatch.WAZE_KEY_NAME
if (key != com.rfsentinel.app.util.SecureStore.get(this, name).orEmpty()) com.rfsentinel.app.util.SecureStore.put(this, name, key)
}
- val presets = mutableSetOf<String>()
- if (binding.presetGlobal.isChecked) presets.add("global")
- if (binding.presetCanada.isChecked) presets.add("canada")
- if (binding.presetUs.isChecked) presets.add("us")
- if (binding.presetFrance.isChecked) presets.add("france")
- if (binding.presetUk.isChecked) presets.add("uk")
- if (binding.presetPortugal.isChecked) presets.add("portugal")
- if (binding.presetGermany.isChecked) presets.add("germany")
- if (binding.presetSpain.isChecked) presets.add("spain")
- if (binding.presetItaly.isChecked) presets.add("italy")
- OuiWatchlist.setEnabledPresets(this, presets)
-
- Prefs.setAlertThreshold(
- this,
- when (binding.thresholdGroup.checkedRadioButtonId) {
- R.id.thresholdWeak -> 0
- R.id.thresholdStrong -> 80
- else -> 50
- }
- )
+ OuiWatchlist.setEnabledPresets(this, presetSwitches().filterValues { it.isChecked }.keys)
+
+ Prefs.setAlertThreshold(this, intArrayOf(0, 50, 80).getOrElse(binding.thresholdGroup.checkedIndex) { 50 })
Prefs.setSoundEnabled(this, binding.soundSwitch.isChecked)
Prefs.setRadarNorthUp(this, binding.radarTopGroup.checkedIndex == 1)
Prefs.setRadarSpinDots(this, binding.radarDotsGroup.checkedIndex == 1)
@@ -3014,11 +2932,7 @@ class SettingsActivity : AppCompatActivity() {
Prefs.setTraceEveryPing(this, binding.traceEveryPingSwitch.isChecked)
Prefs.setOuiSpyRelayAll(this, binding.ouiSpyRelaySwitch.isChecked)
Prefs.setOuiSpyPhoneBle(this, binding.ouiSpyPhoneBleSwitch.isChecked)
- Prefs.setScreenMode(this, when (binding.screenModeGroup.checkedRadioButtonId) {
- R.id.screenAlwaysOn -> Prefs.ScreenMode.ALWAYS_ON
- R.id.screenNormal -> Prefs.ScreenMode.NORMAL
- else -> Prefs.ScreenMode.ON_WHILE_CHARGING
- })
+ Prefs.setScreenMode(this, Prefs.ScreenMode.entries.getOrElse(binding.screenModeGroup.checkedIndex) { Prefs.ScreenMode.ON_WHILE_CHARGING })
com.rfsentinel.app.ui.ScreenAwake.apply(this)
Prefs.setKnownAlprAlerts(this, binding.knownAlprSwitch.isChecked)
Prefs.setCellChangeAlerts(this, binding.cellChangeSwitch.isChecked)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/AircraftActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/AircraftActivity.kt
index 9cf6859..3dc1736 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/AircraftActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/AircraftActivity.kt
@@ -2,29 +2,17 @@ package com.rfsentinel.app.ui
import android.annotation.SuppressLint
import android.content.Intent
-import android.graphics.Typeface
import android.os.Bundle
-import android.view.LayoutInflater
import android.view.View
-import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
-import androidx.lifecycle.Lifecycle
-import androidx.lifecycle.lifecycleScope
-import androidx.lifecycle.repeatOnLifecycle
-import androidx.recyclerview.widget.LinearLayoutManager
-import androidx.recyclerview.widget.RecyclerView
import com.rfsentinel.app.databinding.ActivityLogBinding
-import com.rfsentinel.app.databinding.ItemDetectionBinding
import com.rfsentinel.app.online.PoliceAircraft
import com.rfsentinel.app.sdr.SdrRadio
import com.rfsentinel.app.service.DeviceRegistry
import com.rfsentinel.app.service.ScanForegroundService
import com.rfsentinel.app.util.Units
-import com.rfsentinel.app.util.applySystemBarInsets
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.launch
import java.util.Locale
import kotlin.math.atan2
import kotlin.math.cos
@@ -45,42 +33,23 @@ class AircraftActivity : AppCompatActivity() {
private var rows: List<Row> = emptyList()
private val demo get() = com.rfsentinel.app.BuildConfig.DEBUG && intent.getBooleanExtra("demo", false)
- private val adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
- override fun getItemCount() = rows.size
- override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
- object : RecyclerView.ViewHolder(ItemDetectionBinding.inflate(LayoutInflater.from(parent.context), parent, false).root) {}
-
- override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
- val r = rows[position]
- val p = r.seen.plane
- ItemDetectionBinding.bind(holder.itemView).apply {
- labelText.text = name(p) + if (r.seen.hit != null) " · ${r.seen.hit.label}" else ""
- labelText.setTextColor(if (r.seen.hit != null) POLICE else macText.currentTextColor)
- macText.text = listOfNotNull(p.type, p.owner, p.registration?.takeIf { it != name(p) }).joinToString(" · ").ifEmpty { p.hex.uppercase() }
- metaText.text = listOfNotNull(
- r.distanceKm?.let { Units.distance(it * 1000) + (r.bearingDeg?.let { b -> " ${compass(b)}" } ?: "") },
- altitude(p), p.speedKt?.let { String.format(Locale.US, "%.0f kt", it) }, p.trackDeg?.let { "heading ${it.toInt()}°" }
- ).joinToString(" · ")
- }
- holder.itemView.setOnClickListener { openOnMap(p) }
- }
+ private val adapter = DetectionRows({ rows }) { r ->
+ val p = r.seen.plane
+ labelText.text = name(p) + if (r.seen.hit != null) " · ${r.seen.hit.label}" else ""
+ labelText.setTextColor(if (r.seen.hit != null) POLICE else macText.currentTextColor)
+ macText.text = listOfNotNull(p.type, p.owner, p.registration?.takeIf { it != name(p) }).joinToString(" · ").ifEmpty { p.hex.uppercase() }
+ metaText.text = listOfNotNull(
+ r.distanceKm?.let { Units.distance(it * 1000) + (r.bearingDeg?.let { b -> " ${compass(b)}" } ?: "") },
+ altitude(p), p.speedKt?.let { String.format(Locale.US, "%.0f kt", it) }, p.trackDeg?.let { "heading ${it.toInt()}°" }
+ ).joinToString(" · ")
+ root.setOnClickListener { openOnMap(p) }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
- binding = ActivityLogBinding.inflate(layoutInflater)
- setContentView(binding.root)
- binding.root.applySystemBarInsets()
- title = "Aircraft"
- supportActionBar?.setDisplayHomeAsUpEnabled(true)
- binding.recyclerView.layoutManager = LinearLayoutManager(this)
- binding.recyclerView.adapter = adapter
+ binding = logScreen("Aircraft", adapter)
binding.root.addView(visual.root, 0)
- lifecycleScope.launch {
- repeatOnLifecycle(Lifecycle.State.STARTED) {
- while (true) { refresh(); delay(1_000) }
- }
- }
+ refreshWhileStarted(1_000) { refresh() }
}
override fun onSupportNavigateUp(): Boolean { finish(); return true }
@@ -112,24 +81,12 @@ class AircraftActivity : AppCompatActivity() {
var lastCount = -1L
var lastAt = 0L
- fun title(t: String) = TextView(ctx).apply {
- text = t; textSize = 12f; setTypeface(typeface, Typeface.BOLD); setTextColor(accent); letterSpacing = 0.08f
- }
-
- fun card(vararg views: View) = LinearLayout(ctx).apply {
- orientation = LinearLayout.VERTICAL
- background = VisualMode.card(ctx)
- val p = (12 * dp).toInt(); setPadding(p, p, p, p)
- views.forEach { addView(it) }
- layoutParams = LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = (10 * dp).toInt() }
- }
-
init {
box.addView(VisualMode.tileRow(ctx, tiles).apply {
layoutParams = LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = (10 * dp).toInt() }
})
- box.addView(card(title("RADAR · NORTH UP"), radar, sources))
- rateCard = card(title("RTL-SDR · ADS-B MESSAGES PER SECOND"), rate, rateText)
+ box.addView(visualCard(visualTitle("RADAR · NORTH UP"), radar, sources))
+ rateCard = visualCard(visualTitle("RTL-SDR · ADS-B MESSAGES PER SECOND"), rate, rateText)
box.addView(rateCard)
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/AntennaCheckActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/AntennaCheckActivity.kt
index 1bbdb8e..d284b93 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/AntennaCheckActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/AntennaCheckActivity.kt
@@ -4,24 +4,15 @@ import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
-import android.view.LayoutInflater
import android.view.View
-import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
-import androidx.lifecycle.Lifecycle
-import androidx.lifecycle.lifecycleScope
-import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
-import androidx.recyclerview.widget.RecyclerView
import com.rfsentinel.app.databinding.ActivityAntennaCheckBinding
-import com.rfsentinel.app.databinding.ItemDetectionBinding
import com.rfsentinel.app.service.ScanForegroundService
import com.rfsentinel.app.usb.AntennaCheck
import com.rfsentinel.app.usb.UsbWifi
import com.rfsentinel.app.R
import com.rfsentinel.app.util.applySystemBarInsets
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.launch
/**
* Antenna check for the USB WiFi adapter (after Wardrive Go's): pick a nearby access point as
@@ -53,21 +44,12 @@ class AntennaCheckActivity : AppCompatActivity() {
/** Checking the USB Bluetooth adapter's antennas instead of the USB WiFi adapter's. */
private var bt = false
- private val adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
- init { setHasStableIds(true) } // rows stay put across refreshes, so a tap isn't lost to a rebind
- override fun getItemCount() = aps.size
- override fun getItemId(position: Int) = aps[position].bssid.hashCode().toLong()
- override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
- object : RecyclerView.ViewHolder(ItemDetectionBinding.inflate(LayoutInflater.from(parent.context), parent, false).root) {}
- override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
- val ap = aps[position]
- ItemDetectionBinding.bind(holder.itemView).apply {
- labelText.text = ap.ssid ?: if (bt) "Unnamed device" else "Hidden network"
- macText.text = ap.bssid
- metaText.text = "${AntennaCheck.channelName(ap.channel)} · ${ap.rssi} dBm"
- }
- holder.itemView.setOnClickListener { pick(ap) }
- }
+ // Stable IDs keep a tap on the same access point across refreshes.
+ private val adapter = DetectionRows({ aps }, id = { it.bssid.hashCode().toLong() }) { ap ->
+ labelText.text = ap.ssid ?: if (bt) "Unnamed device" else "Hidden network"
+ macText.text = ap.bssid
+ metaText.text = "${AntennaCheck.channelName(ap.channel)} · ${ap.rssi} dBm"
+ root.setOnClickListener { pick(ap) }
}
override fun onCreate(savedInstanceState: Bundle?) {
@@ -101,11 +83,7 @@ class AntennaCheckActivity : AppCompatActivity() {
}
styleCards()
demo = com.rfsentinel.app.BuildConfig.DEBUG && intent.getBooleanExtra("demo", false)
- lifecycleScope.launch {
- repeatOnLifecycle(Lifecycle.State.STARTED) {
- while (true) { if (demo) feedDemo(); refresh(); delay(500) }
- }
- }
+ refreshWhileStarted(500) { if (demo) feedDemo(); refresh() }
}
override fun onStart() {
diff --git a/app/src/main/java/com/rfsentinel/app/ui/CellTowersActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/CellTowersActivity.kt
index 40b4bc7..52ea30c 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/CellTowersActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/CellTowersActivity.kt
@@ -8,10 +8,7 @@ import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
-import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
-import androidx.lifecycle.repeatOnLifecycle
-import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.rfsentinel.app.databinding.ActivityLogBinding
@@ -21,8 +18,6 @@ import com.rfsentinel.app.service.CellMonitor
import com.rfsentinel.app.service.CellTowerStore
import com.rfsentinel.app.service.ScanForegroundService
import com.rfsentinel.app.util.Permissions
-import com.rfsentinel.app.util.applySystemBarInsets
-import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.text.DateFormat
import java.util.Date
@@ -101,22 +96,9 @@ class CellTowersActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
- binding = ActivityLogBinding.inflate(layoutInflater)
- setContentView(binding.root)
- binding.root.applySystemBarInsets()
- title = "Cell towers"
- supportActionBar?.setDisplayHomeAsUpEnabled(true)
- binding.recyclerView.layoutManager = LinearLayoutManager(this)
- binding.recyclerView.adapter = adapter
+ binding = logScreen("Cell towers", adapter)
- lifecycleScope.launch {
- repeatOnLifecycle(Lifecycle.State.STARTED) {
- while (true) {
- refresh()
- delay(REFRESH_MS)
- }
- }
- }
+ refreshWhileStarted(REFRESH_MS) { refresh() }
}
override fun onDestroy() {
diff --git a/app/src/main/java/com/rfsentinel/app/ui/CustomColors.kt b/app/src/main/java/com/rfsentinel/app/ui/CustomColors.kt
index 11abee9..74b253d 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/CustomColors.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/CustomColors.kt
@@ -8,7 +8,6 @@ import android.app.Activity
import android.content.Context
import android.content.res.Configuration
import android.os.Build
-import androidx.annotation.ColorInt
import com.google.android.material.color.ColorResourcesOverride
import com.google.android.material.color.MaterialColorUtilitiesHelper
import com.google.android.material.color.ThemeUtils
@@ -132,5 +131,4 @@ object CustomColors {
}
}
- @ColorInt fun accentOf(t: CustomTheme): Int = t.accent
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt
index 8fab560..864a0ce 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceAdapter.kt
@@ -98,6 +98,15 @@ class DeviceAdapter(
private var animator: ValueAnimator? = null
private var animColor = 0
+ init {
+ binding.root.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
+ override fun onViewAttachedToWindow(view: View) {
+ currentList.getOrNull(bindingAdapterPosition)?.let { setHighlight(it.highlight, it.flashing) }
+ }
+ override fun onViewDetachedFromWindow(view: View) = stopFlash()
+ })
+ }
+
/**
* Pulses the row background while flashing. A running pulse of the same
* colour is left alone on rebind (rows rebind every second as RSSI and
@@ -111,7 +120,7 @@ class DeviceAdapter(
}
val low = (color and 0x00FFFFFF) or 0x26000000
val high = (color and 0x00FFFFFF) or 0xE6000000.toInt()
- if (flashing) {
+ if (flashing && binding.root.isAttachedToWindow) {
if (animator?.isRunning == true && animColor == color) return
stopFlash()
animColor = color
@@ -156,7 +165,7 @@ class DeviceAdapter(
b.tagText.visibility = View.GONE
}
b.titleText.text = row.title
- b.titleText.setTypeface(null, if (row.bold) Typeface.BOLD else Typeface.NORMAL)
+ b.titleText.setTypeface(b.titleText.typeface, if (row.bold) Typeface.BOLD else Typeface.NORMAL)
b.macText.text = row.subtitle
b.metaText.text = metaWithBadges(row)
val conf = row.confidence
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
index 48d49ca..5209e2d 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
@@ -10,9 +10,7 @@ import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
-import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
-import androidx.lifecycle.repeatOnLifecycle
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.rfsentinel.app.data.AppDatabase
@@ -31,8 +29,6 @@ import com.rfsentinel.app.util.MacUtil
import com.rfsentinel.app.util.ProximityUtil
import com.rfsentinel.app.util.applySystemBarInsets
import com.rfsentinel.app.util.Prefs
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.text.DateFormat
import java.util.Date
@@ -139,14 +135,7 @@ class DeviceDetailActivity : AppCompatActivity() {
sectionsKey = ""
refresh()
}
- lifecycleScope.launch {
- repeatOnLifecycle(Lifecycle.State.STARTED) {
- while (isActive) {
- refresh()
- delay(1000)
- }
- }
- }
+ refreshWhileStarted(1000) { refresh() }
}
override fun onSupportNavigateUp(): Boolean {
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.kt
index 1347bac..a545264 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.kt
@@ -12,18 +12,17 @@ import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DiffUtil
-import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.chip.Chip
import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import com.rfsentinel.app.R
import com.rfsentinel.app.data.AppDatabase
import com.rfsentinel.app.data.KnownDeviceDao
import com.rfsentinel.app.data.KnownDeviceEntity
-import com.rfsentinel.app.databinding.ActivityDeviceHistoryBinding
+import com.rfsentinel.app.databinding.ActivityLogBinding
import com.rfsentinel.app.detect.DeviceIntel
import com.rfsentinel.app.util.Prefs
-import com.rfsentinel.app.util.applySystemBarInsets
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@@ -37,21 +36,20 @@ class DeviceHistoryActivity : AppCompatActivity() {
private enum class Filter(val label: String) { ALL("All"), FAVORITES("Favorites"), FLAGGED("Flagged before"), TODAY("Seen today") }
- private lateinit var binding: ActivityDeviceHistoryBinding
+ private lateinit var binding: ActivityLogBinding
+ private lateinit var keptText: TextView
private val adapter = Rows { DeviceActions.openDetails(this, it.mac) }
private var filter = Filter.ALL
private var searchJob: Job? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
- binding = ActivityDeviceHistoryBinding.inflate(layoutInflater)
- setContentView(binding.root)
- binding.root.applySystemBarInsets()
- title = "Device history"
- supportActionBar?.setDisplayHomeAsUpEnabled(true)
-
- binding.recyclerView.layoutManager = LinearLayoutManager(this)
- binding.recyclerView.adapter = adapter
+ binding = logScreen("Device history", adapter)
+ binding.searchLayout.hint = "Search MAC, name, vendor, type, note"
+ binding.emptyText.text = ""
+ binding.emptyText.visibility = View.GONE
+ keptText = layoutInflater.inflate(R.layout.view_history_retention, binding.root, false) as TextView
+ binding.root.addView(keptText)
for (f in Filter.entries) {
val chip = FitChip(this).apply {
id = View.generateViewId(); text = f.label; isCheckable = true; isCheckedIconVisible = false
@@ -63,7 +61,7 @@ class DeviceHistoryActivity : AppCompatActivity() {
}
binding.searchInput.doAfterTextChanged { search(now = false) }
if (intent.getBooleanExtra(EXTRA_IMPORT, false) && savedInstanceState == null) binding.root.post { pickFile() }
- binding.keptText.setOnClickListener {
+ keptText.setOnClickListener {
startActivity(Intent(this, com.rfsentinel.app.settings.SettingsActivity::class.java)
.putExtra(com.rfsentinel.app.settings.SettingsActivity.EXTRA_SECTION, com.rfsentinel.app.settings.SettingsActivity.SECTION_DATA))
}
@@ -73,7 +71,7 @@ class DeviceHistoryActivity : AppCompatActivity() {
super.onResume()
// Back from a device's page (a note, a favorite) or Settings: up to date.
val days = Prefs.retentionDays(this)
- binding.keptText.text = (if (days <= 0) "History is kept forever" else "History is kept for $days days") +
+ keptText.text = (if (days <= 0) "History is kept forever" else "History is kept for $days days") +
" (change in Settings > Data)"
search(now = true)
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DiagnosticUi.kt b/app/src/main/java/com/rfsentinel/app/ui/DiagnosticUi.kt
new file mode 100644
index 0000000..a444bb1
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/DiagnosticUi.kt
@@ -0,0 +1,69 @@
+package com.rfsentinel.app.ui
+
+import android.graphics.Typeface
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.LinearLayout
+import android.widget.TextView
+import androidx.appcompat.app.AppCompatActivity
+import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.lifecycleScope
+import androidx.lifecycle.repeatOnLifecycle
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import com.rfsentinel.app.databinding.ActivityLogBinding
+import com.rfsentinel.app.databinding.ItemDetectionBinding
+import com.rfsentinel.app.util.applySystemBarInsets
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+
+internal fun AppCompatActivity.logScreen(name: String, adapter: RecyclerView.Adapter<*>) =
+ ActivityLogBinding.inflate(layoutInflater).also {
+ setContentView(it.root)
+ it.root.applySystemBarInsets()
+ title = name
+ supportActionBar?.setDisplayHomeAsUpEnabled(true)
+ it.recyclerView.layoutManager = LinearLayoutManager(this)
+ it.recyclerView.adapter = adapter
+ }
+
+internal fun AppCompatActivity.refreshWhileStarted(interval: Long, refresh: suspend () -> Unit) {
+ lifecycleScope.launch {
+ repeatOnLifecycle(Lifecycle.State.STARTED) {
+ while (true) { refresh(); delay(interval) }
+ }
+ }
+}
+
+internal class DetectionRows<T>(
+ private val items: () -> List<T>,
+ private val id: ((T) -> Long)? = null,
+ private val bind: ItemDetectionBinding.(T) -> Unit
+) : RecyclerView.Adapter<DetectionRows.Holder>() {
+ class Holder(val binding: ItemDetectionBinding) : RecyclerView.ViewHolder(binding.root)
+ init { setHasStableIds(id != null) }
+ override fun getItemCount() = items().size
+ override fun getItemId(position: Int) = id?.invoke(items()[position]) ?: RecyclerView.NO_ID
+ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
+ Holder(ItemDetectionBinding.inflate(LayoutInflater.from(parent.context), parent, false))
+ override fun onBindViewHolder(holder: Holder, position: Int) = holder.binding.bind(items()[position])
+}
+
+internal fun AppCompatActivity.visualTitle(label: String) = TextView(this).apply {
+ text = label
+ textSize = 12f
+ setTypeface(typeface, Typeface.BOLD)
+ setTextColor(ChipStyle.accent(context).first)
+ letterSpacing = 0.08f
+}
+
+internal fun AppCompatActivity.visualCard(vararg views: View) = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ background = VisualMode.card(context)
+ val dp = resources.displayMetrics.density
+ val padding = (12 * dp).toInt()
+ setPadding(padding, padding, padding, padding)
+ views.forEach { addView(it) }
+ layoutParams = LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = (10 * dp).toInt() }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt
index 8b408f0..0e00b9e 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt
@@ -11,19 +11,12 @@ import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
-import androidx.lifecycle.Lifecycle
-import androidx.lifecycle.lifecycleScope
-import androidx.lifecycle.repeatOnLifecycle
-import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.rfsentinel.app.databinding.ActivityLogBinding
import com.rfsentinel.app.databinding.ItemDetectionBinding
import com.rfsentinel.app.detect.GnssAnalyzer
import com.rfsentinel.app.service.GnssWatch
import com.rfsentinel.app.util.Permissions
-import com.rfsentinel.app.util.applySystemBarInsets
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.launch
/**
* The satellites the phone hears, for every system (GPS, GLONASS, Galileo, BeiDou, QZSS,
@@ -68,19 +61,9 @@ class GnssActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
- binding = ActivityLogBinding.inflate(layoutInflater)
- setContentView(binding.root)
- binding.root.applySystemBarInsets()
- title = "Satellites"
- supportActionBar?.setDisplayHomeAsUpEnabled(true)
- binding.recyclerView.layoutManager = LinearLayoutManager(this)
- binding.recyclerView.adapter = adapter
+ binding = logScreen("Satellites", adapter)
binding.root.addView(visual.root, 0)
- lifecycleScope.launch {
- repeatOnLifecycle(Lifecycle.State.STARTED) {
- while (true) { refresh(); delay(1_000) }
- }
- }
+ refreshWhileStarted(1_000) { refresh() }
}
@SuppressLint("MissingPermission")
@@ -127,23 +110,11 @@ class GnssActivity : AppCompatActivity() {
val bars = SatBarsView(this@GnssActivity)
var legendKey = ""
- fun title(t: String) = TextView(this@GnssActivity).apply {
- text = t; textSize = 12f; setTypeface(typeface, Typeface.BOLD); setTextColor(accent); letterSpacing = 0.08f
- }
-
- fun card(vararg views: View) = android.widget.LinearLayout(this@GnssActivity).apply {
- orientation = android.widget.LinearLayout.VERTICAL
- background = VisualMode.card(this@GnssActivity)
- val p = (12 * dp).toInt(); setPadding(p, p, p, p)
- views.forEach { addView(it) }
- layoutParams = android.widget.LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = (10 * dp).toInt() }
- }
-
init {
- box.addView(card(title("CHECK"), verdict, verdictSub))
+ box.addView(visualCard(visualTitle("CHECK"), verdict, verdictSub))
box.addView(tiles, android.widget.LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = (10 * dp).toInt() })
- box.addView(card(title("SKY · NORTH UP"), sky, legend))
- box.addView(card(title("SIGNAL PER SATELLITE · dB-Hz"), bars,
+ box.addView(visualCard(visualTitle("SKY · NORTH UP"), sky, legend))
+ box.addView(visualCard(visualTitle("SIGNAL PER SATELLITE · dB-Hz"), bars,
TextView(this@GnssActivity).apply { text = "Filled: used for your position. Outlined: heard only."; textSize = 12f; alpha = 0.7f }))
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapGps.kt b/app/src/main/java/com/rfsentinel/app/ui/MapGps.kt
index ee20287..035e849 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapGps.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapGps.kt
@@ -61,8 +61,6 @@ object MapGps {
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 ->
diff --git a/app/src/main/java/com/rfsentinel/app/ui/P25Activity.kt b/app/src/main/java/com/rfsentinel/app/ui/P25Activity.kt
index 99bb49d..c8623eb 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/P25Activity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/P25Activity.kt
@@ -11,10 +11,7 @@ import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doAfterTextChanged
-import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
-import androidx.lifecycle.repeatOnLifecycle
-import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.rfsentinel.app.databinding.ActivityLogBinding
import com.rfsentinel.app.databinding.ItemDetectionBinding
@@ -23,9 +20,7 @@ import com.rfsentinel.app.sdr.P25Log
import com.rfsentinel.app.sdr.P25Tsbk
import com.rfsentinel.app.sdr.SdrRadio
import com.rfsentinel.app.util.Prefs
-import com.rfsentinel.app.util.applySystemBarInsets
import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import kotlinx.coroutines.launch
import java.util.Locale
@@ -84,20 +79,10 @@ class P25Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
- binding = ActivityLogBinding.inflate(layoutInflater)
- setContentView(binding.root)
- binding.root.applySystemBarInsets()
- title = "P25 talkgroups"
- supportActionBar?.setDisplayHomeAsUpEnabled(true)
+ binding = logScreen("P25 talkgroups", adapter)
binding.searchInput.doAfterTextChanged { refresh() }
binding.root.addView(header, 2)
- binding.recyclerView.layoutManager = LinearLayoutManager(this)
- binding.recyclerView.adapter = adapter
- lifecycleScope.launch {
- repeatOnLifecycle(Lifecycle.State.STARTED) {
- while (true) { refresh(); delay(1_000) }
- }
- }
+ refreshWhileStarted(1_000) { refresh() }
}
override fun onSupportNavigateUp(): Boolean { finish(); return true }
diff --git a/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt
index 9a1dde3..ee72a90 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/SentinelLinkActivity.kt
@@ -17,9 +17,6 @@ import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
-import androidx.lifecycle.Lifecycle
-import androidx.lifecycle.lifecycleScope
-import androidx.lifecycle.repeatOnLifecycle
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.slider.Slider
@@ -29,8 +26,6 @@ import com.rfsentinel.app.link.MeshNode
import com.rfsentinel.app.link.PhoneLink
import com.rfsentinel.app.service.ScanForegroundService
import com.rfsentinel.app.util.applySystemBarInsets
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.launch
/**
* Sentinel Link: this phone's name, sharing on / off, linking a new phone ("Link up a Sentinel" on one,
@@ -126,11 +121,7 @@ class SentinelLinkActivity : AppCompatActivity() {
setContentView(scroll)
scroll.applySystemBarInsets()
- lifecycleScope.launch {
- repeatOnLifecycle(Lifecycle.State.STARTED) {
- while (true) { refresh(); delay(5_000) }
- }
- }
+ refreshWhileStarted(5_000) { refresh() }
}
override fun onStart() {
diff --git a/app/src/main/java/com/rfsentinel/app/ui/SnapshotActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/SnapshotActivity.kt
index 4c80217..221e958 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/SnapshotActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/SnapshotActivity.kt
@@ -9,7 +9,6 @@ import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.lifecycleScope
-import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.chip.Chip
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.rfsentinel.app.data.AppDatabase
@@ -18,7 +17,6 @@ import com.rfsentinel.app.data.TripEntity
import com.rfsentinel.app.databinding.ActivityLogBinding
import com.rfsentinel.app.detect.DeviceIntel
import com.rfsentinel.app.util.Exporter
-import com.rfsentinel.app.util.applySystemBarInsets
import kotlinx.coroutines.launch
import java.text.DateFormat
import java.util.Date
@@ -48,13 +46,7 @@ class SnapshotActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
tripId = intent.getLongExtra(EXTRA_TRIP_ID, 0L)
- binding = ActivityLogBinding.inflate(layoutInflater)
- setContentView(binding.root)
- binding.root.applySystemBarInsets()
- title = "Snapshot"
- supportActionBar?.setDisplayHomeAsUpEnabled(true)
- binding.recyclerView.layoutManager = LinearLayoutManager(this)
- binding.recyclerView.adapter = adapter
+ binding = logScreen("Snapshot", adapter)
// As the main list: room under the last row.
binding.recyclerView.clipToPadding = false
binding.recyclerView.setPadding(0, 0, 0, (8 * resources.displayMetrics.density).toInt())
diff --git a/app/src/main/java/com/rfsentinel/app/ui/TripsActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/TripsActivity.kt
index aa103ba..1f16cd2 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/TripsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/TripsActivity.kt
@@ -10,7 +10,6 @@ import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DiffUtil
-import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
@@ -20,7 +19,6 @@ import com.rfsentinel.app.databinding.ActivityLogBinding
import com.rfsentinel.app.databinding.ItemDetectionBinding
import com.rfsentinel.app.service.TripRecorder
import com.rfsentinel.app.util.Exporter
-import com.rfsentinel.app.util.applySystemBarInsets
import kotlinx.coroutines.launch
import java.text.DateFormat
import java.util.Date
@@ -93,12 +91,7 @@ class TripsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
- binding = ActivityLogBinding.inflate(layoutInflater)
- setContentView(binding.root)
- binding.root.applySystemBarInsets()
- supportActionBar?.setDisplayHomeAsUpEnabled(true)
- binding.recyclerView.layoutManager = LinearLayoutManager(this)
- binding.recyclerView.adapter = adapter
+ binding = logScreen("Recorded traces", adapter)
section = savedInstanceState?.getString(EXTRA_SECTION) ?: intent.getStringExtra(EXTRA_SECTION) ?: TripEntity.KIND_TRACE
for ((kind, label) in listOf(TripEntity.KIND_TRACE to "Traces", TripEntity.KIND_SNAPSHOT to "Snapshots")) {
binding.filterChips.addView(com.rfsentinel.app.ui.FitChip(this).apply {
@@ -211,31 +204,16 @@ class TripsActivity : AppCompatActivity() {
}
private fun actions(t: TripEntity) {
- if (t.snapshot) {
- MaterialAlertDialogBuilder(this)
- .setTitle(t.name)
- .setItems(arrayOf("View list", "View on map", "Export (GPX, KML, GeoJSON, CSV)...", "Rename", "Delete")) { _, which ->
- when (which) {
- 0 -> open(t)
- 1 -> startActivity(Intent(this, MapActivity::class.java).putExtra(MapActivity.EXTRA_TRIP_ID, t.id))
- 2 -> Exporter.showTripExport(this, t.id, snapshot = true)
- 3 -> rename(t)
- 4 -> delete(t)
- }
- }
- .show()
- return
+ val choices = buildList<Pair<String, () -> Unit>> {
+ if (t.snapshot) add("View list" to { open(t) })
+ add("View on map" to { startActivity(Intent(this@TripsActivity, MapActivity::class.java).putExtra(MapActivity.EXTRA_TRIP_ID, t.id)) })
+ add("Export (GPX, KML, GeoJSON, CSV)..." to { Exporter.showTripExport(this@TripsActivity, t.id, snapshot = t.snapshot) })
+ add("Rename" to { rename(t) })
+ add("Delete" to { delete(t) })
}
MaterialAlertDialogBuilder(this)
.setTitle(t.name)
- .setItems(arrayOf("View on map", "Export (GPX, KML, GeoJSON, CSV)...", "Rename", "Delete")) { _, which ->
- when (which) {
- 0 -> startActivity(Intent(this, MapActivity::class.java).putExtra(MapActivity.EXTRA_TRIP_ID, t.id))
- 1 -> Exporter.showTripExport(this, t.id)
- 2 -> rename(t)
- 3 -> delete(t)
- }
- }
+ .setItems(choices.map { it.first }.toTypedArray()) { _, which -> choices[which].second() }
.show()
}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.kt
index 28e251f..d5505a2 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/WaterfallActivity.kt
@@ -6,9 +6,6 @@ import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
-import androidx.lifecycle.Lifecycle
-import androidx.lifecycle.lifecycleScope
-import androidx.lifecycle.repeatOnLifecycle
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.rfsentinel.app.databinding.ActivityWaterfallBinding
import com.rfsentinel.app.sdr.FreqNames
@@ -16,8 +13,6 @@ import com.rfsentinel.app.sdr.RadioWatch
import com.rfsentinel.app.sdr.SdrRadio
import com.rfsentinel.app.sdr.SdrWaterfall
import com.rfsentinel.app.util.applySystemBarInsets
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.launch
import java.util.Locale
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.atomic.AtomicBoolean
@@ -53,11 +48,7 @@ class WaterfallActivity : AppCompatActivity() {
binding.sweepButton.setOnClickListener { SdrRadio.tuneHz = null; refresh() }
// Opened from a radio transmission's Locate: straight to its frequency (not again after a rotation).
if (savedInstanceState == null) intent.getLongExtra(EXTRA_TUNE_HZ, 0L).takeIf { it > 0 }?.let { zoom(it) }
- lifecycleScope.launch {
- repeatOnLifecycle(Lifecycle.State.STARTED) {
- while (true) { refresh(); delay(1000) }
- }
- }
+ refreshWhileStarted(1000) { refresh() }
}
override fun onStart() {
diff --git a/app/src/main/java/com/rfsentinel/app/ui/WazeStatusActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/WazeStatusActivity.kt
index d9b1f4b..6b52527 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/WazeStatusActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/WazeStatusActivity.kt
@@ -6,9 +6,6 @@ import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
-import androidx.lifecycle.Lifecycle
-import androidx.lifecycle.lifecycleScope
-import androidx.lifecycle.repeatOnLifecycle
import com.google.android.material.button.MaterialButton
import com.rfsentinel.app.online.MotionTracker
import com.rfsentinel.app.online.OnlineWatch
@@ -20,8 +17,6 @@ import com.rfsentinel.app.service.ScanForegroundService
import com.rfsentinel.app.util.Prefs
import com.rfsentinel.app.util.SecureStore
import com.rfsentinel.app.util.applySystemBarInsets
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.launch
import java.util.Locale
/**
@@ -70,11 +65,7 @@ class WazeStatusActivity : AppCompatActivity() {
setContentView(scroll)
scroll.applySystemBarInsets()
- lifecycleScope.launch {
- repeatOnLifecycle(Lifecycle.State.STARTED) {
- while (true) { refresh(); delay(1_000) }
- }
- }
+ refreshWhileStarted(1_000) { refresh() }
}
override fun onSupportNavigateUp(): Boolean { finish(); return true }
@@ -106,22 +97,10 @@ class WazeStatusActivity : AppCompatActivity() {
val out = TextView(ctx).apply { textSize = 13f; setLineSpacing(0f, 1.15f); setTextIsSelectable(true) }
val answer = TextView(ctx).apply { textSize = 12f; alpha = 0.8f; setTextIsSelectable(true) }
- fun title(t: String) = TextView(ctx).apply {
- text = t; textSize = 12f; setTypeface(typeface, android.graphics.Typeface.BOLD); setTextColor(accent); letterSpacing = 0.08f
- }
-
- fun card(vararg views: View) = LinearLayout(ctx).apply {
- orientation = LinearLayout.VERTICAL
- background = VisualMode.card(ctx)
- val p = (12 * dp).toInt(); setPadding(p, p, p, p)
- views.forEach { addView(it) }
- layoutParams = LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = (10 * dp).toInt() }
- }
-
init {
val head = LinearLayout(ctx).apply {
orientation = LinearLayout.HORIZONTAL; gravity = android.view.Gravity.CENTER_VERTICAL
- addView(title("WAZE CHECKS"), LinearLayout.LayoutParams(0, -2, 1f))
+ addView(visualTitle("WAZE CHECKS"), LinearLayout.LayoutParams(0, -2, 1f))
addView(stateChip)
}
val timing = LinearLayout(ctx).apply {
@@ -131,13 +110,13 @@ class WazeStatusActivity : AppCompatActivity() {
LinearLayout.LayoutParams(0, -2, 1f))
setPadding(0, (8 * dp).toInt(), 0, 0)
}
- box.addView(card(head, source, timing))
+ box.addView(visualCard(head, source, timing))
box.addView(VisualMode.tileRow(ctx, tiles).apply {
layoutParams = LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = (10 * dp).toInt() }
})
- box.addView(card(title("LAST CHECKS"), timeline, timelineNote))
- box.addView(card(title("WHAT GOES OUT"), out))
- box.addView(card(title("LAST ANSWER"), answer))
+ box.addView(visualCard(visualTitle("LAST CHECKS"), timeline, timelineNote))
+ box.addView(visualCard(visualTitle("WHAT GOES OUT"), out))
+ box.addView(visualCard(visualTitle("LAST ANSWER"), answer))
}
fun value(tile: View, v: String) { ((tile as LinearLayout).getChildAt(0) as TextView).text = v }
diff --git a/app/src/main/java/com/rfsentinel/app/ui/WifiAnalyzerActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/WifiAnalyzerActivity.kt
index 66cde42..4786097 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/WifiAnalyzerActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/WifiAnalyzerActivity.kt
@@ -9,26 +9,17 @@ import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.os.SystemClock
-import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
-import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
-import androidx.lifecycle.Lifecycle
-import androidx.lifecycle.lifecycleScope
-import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
-import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.chip.Chip
import com.rfsentinel.app.databinding.ActivityWifiAnalyzerBinding
-import com.rfsentinel.app.databinding.ItemDetectionBinding
import com.rfsentinel.app.ui.WifiChartView.Ap
import com.rfsentinel.app.ui.WifiChartView.Band
import com.rfsentinel.app.util.applySystemBarInsets
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.launch
/**
* WiFi channel and spectrum analyzer for 2.4, 5 and 6 GHz, from the phone's own
@@ -47,19 +38,12 @@ class WifiAnalyzerActivity : AppCompatActivity() {
override fun onReceive(c: Context?, i: Intent?) = reload()
}
- private val adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
- var items: List<Ap> = emptyList()
- override fun getItemCount() = items.size
- override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
- object : RecyclerView.ViewHolder(ItemDetectionBinding.inflate(LayoutInflater.from(parent.context), parent, false).root) {}
- override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
- val ap = items[position]
- val b = ItemDetectionBinding.bind(holder.itemView)
- b.labelText.text = ap.ssid
- b.macText.text = "${ap.bssid} · ch ${WifiChartView.channelOf(ap.freq)} · ${ap.widthMhz} MHz"
- b.metaText.text = "${ap.rssi} dBm · ${ap.freq} MHz" +
- if (ap.centerFreq > 0 && ap.centerFreq != ap.freq) " · centre ${ap.centerFreq} MHz" else ""
- }
+ private var listed: List<Ap> = emptyList()
+ private val adapter = DetectionRows({ listed }) { ap ->
+ labelText.text = ap.ssid
+ macText.text = "${ap.bssid} · ch ${WifiChartView.channelOf(ap.freq)} · ${ap.widthMhz} MHz"
+ metaText.text = "${ap.rssi} dBm · ${ap.freq} MHz" +
+ if (ap.centerFreq > 0 && ap.centerFreq != ap.freq) " · centre ${ap.centerFreq} MHz" else ""
}
override fun onCreate(savedInstanceState: Bundle?) {
@@ -95,11 +79,7 @@ class WifiAnalyzerActivity : AppCompatActivity() {
binding.recyclerView.layoutManager = LinearLayoutManager(this)
binding.recyclerView.adapter = adapter
- lifecycleScope.launch {
- repeatOnLifecycle(Lifecycle.State.STARTED) {
- while (true) { reload(); delay(5_000) }
- }
- }
+ refreshWhileStarted(5_000) { reload() }
}
override fun onStart() {
@@ -170,7 +150,7 @@ class WifiAnalyzerActivity : AppCompatActivity() {
(busiest?.let { " · busiest channel ${it.key} (${it.value.size})" } ?: "") +
" · strongest ${inBand.first().rssi} dBm"
}
- adapter.items = inBand
+ listed = inBand
adapter.notifyDataSetChanged()
}
diff --git a/app/src/main/java/com/rfsentinel/app/util/DeviceExport.kt b/app/src/main/java/com/rfsentinel/app/util/DeviceExport.kt
index f22d75a..2a06058 100644
--- a/app/src/main/java/com/rfsentinel/app/util/DeviceExport.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/DeviceExport.kt
@@ -12,10 +12,9 @@ import com.rfsentinel.app.detect.DeviceIntel
import com.rfsentinel.app.detect.VendorDb
import com.rfsentinel.app.oui.OuiEntry
import com.rfsentinel.app.service.DeviceRegistry
-import java.text.SimpleDateFormat
-import java.util.Date
+import com.rfsentinel.app.util.ExportText.iso
+import com.rfsentinel.app.util.ExportText.local
import java.util.Locale
-import java.util.TimeZone
/**
* Serializes EVERY device the app knows about - matched or not - for the
@@ -25,9 +24,6 @@ import java.util.TimeZone
object DeviceExport {
private val gson = GsonBuilder().setPrettyPrinting().serializeNulls().create()
- private fun iso(t: Long): String =
- SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }.format(Date(t))
- private fun local(t: Long): String = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date(t))
/** Per-device flags the registry doesn't hold (whitelist / favorite). */
class Flags(val whitelisted: (String) -> Boolean, val favorite: (String) -> Boolean)
diff --git a/app/src/main/java/com/rfsentinel/app/util/ExportText.kt b/app/src/main/java/com/rfsentinel/app/util/ExportText.kt
index d1c360d..59c6f43 100644
--- a/app/src/main/java/com/rfsentinel/app/util/ExportText.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/ExportText.kt
@@ -1,11 +1,24 @@
package com.rfsentinel.app.util
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.TimeZone
+import java.util.Locale
+
/**
* Safe text for exported files. Device names and WiFi SSIDs are chosen by
* whoever owns the device, so exports must treat them as hostile input.
*/
object ExportText {
+ private val utcTime = ThreadLocal.withInitial {
+ SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }
+ }
+ private val localTime = ThreadLocal.withInitial { SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US) }
+
+ internal fun iso(time: Long): String = utcTime.get()!!.format(Date(time))
+ internal fun local(time: Long): String = localTime.get()!!.apply { timeZone = TimeZone.getDefault() }.format(Date(time))
+
/** Characters that make a spreadsheet treat a cell as a formula (CSV/formula injection). */
private val FORMULA_START = charArrayOf('=', '+', '-', '@', '\t', '\r')
diff --git a/app/src/main/java/com/rfsentinel/app/util/Exporter.kt b/app/src/main/java/com/rfsentinel/app/util/Exporter.kt
index 5a6b47a..d507526 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Exporter.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Exporter.kt
@@ -18,7 +18,6 @@ import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
-import java.util.TimeZone
/**
* Exports the match log (CSV with every field, GPX / KML of GPS-tagged
@@ -313,10 +312,9 @@ object Exporter {
}
fun csv(rows: List<DetectionEntity>): String {
- val fmt = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US)
val sb = StringBuilder("timestamp,mac,label,category,confidence,source,rssi,vendor,device_name,evidence,latitude,longitude\n")
rows.forEach { r ->
- sb.append(fmt.format(Date(r.timestamp))).append(',')
+ sb.append(ExportText.local(r.timestamp)).append(',')
.append(r.mac).append(',')
.append(q(r.label)).append(',')
.append(r.category).append(',')
@@ -335,13 +333,12 @@ object Exporter {
private fun q(s: String?): String = ExportText.csv(s)
fun gpx(rows: List<DetectionEntity>): String {
- val iso = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }
val sb = StringBuilder()
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
sb.append("<gpx version=\"1.1\" creator=\"RF Sentinel\" xmlns=\"http://www.topografix.com/GPX/1/1\">\n")
rows.forEach { r ->
sb.append(String.format(Locale.US, " <wpt lat=\"%.7f\" lon=\"%.7f\">\n", r.latitude, r.longitude))
- sb.append(" <time>").append(iso.format(Date(r.timestamp))).append("</time>\n")
+ sb.append(" <time>").append(ExportText.iso(r.timestamp)).append("</time>\n")
sb.append(" <name>").append(x(r.label)).append("</name>\n")
sb.append(" <desc>").append(x("${r.category} ${r.confidence}% - ${r.mac} - ${r.rssi} dBm - ${r.evidence}")).append("</desc>\n")
sb.append(" <type>").append(x(r.category)).append("</type>\n")
@@ -352,14 +349,13 @@ object Exporter {
}
fun kml(rows: List<DetectionEntity>): String {
- val fmt = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US)
val sb = StringBuilder()
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n<Document>\n")
sb.append(" <name>RF Sentinel matches</name>\n")
rows.forEach { r ->
sb.append(" <Placemark>\n")
sb.append(" <name>").append(x(r.label)).append("</name>\n")
- sb.append(" <description>").append(x("${fmt.format(Date(r.timestamp))} - ${r.category} ${r.confidence}% - ${r.mac} - ${r.rssi} dBm")).append("</description>\n")
+ sb.append(" <description>").append(x("${ExportText.local(r.timestamp)} - ${r.category} ${r.confidence}% - ${r.mac} - ${r.rssi} dBm")).append("</description>\n")
sb.append(String.format(Locale.US, " <Point><coordinates>%.7f,%.7f,0</coordinates></Point>\n", r.longitude, r.latitude))
sb.append(" </Placemark>\n")
}
diff --git a/app/src/main/java/com/rfsentinel/app/util/LiveExport.kt b/app/src/main/java/com/rfsentinel/app/util/LiveExport.kt
index 197d03e..d7a86b8 100644
--- a/app/src/main/java/com/rfsentinel/app/util/LiveExport.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/LiveExport.kt
@@ -8,10 +8,7 @@ import com.rfsentinel.app.data.AppDatabase
import com.rfsentinel.app.service.DeviceRegistry
import org.json.JSONArray
import org.json.JSONObject
-import java.text.SimpleDateFormat
import java.util.Date
-import java.util.Locale
-import java.util.TimeZone
/**
* Settings > Data > Live export (off by default): while scanning, keeps three files up to date
@@ -78,8 +75,6 @@ object LiveExport {
return uri
}
- private val iso = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }
-
/** Devices where they were pinpointed, else at the spot they were heard strongest, plus "you are here" (pure; unit-tested). */
fun geoJson(devices: List<DeviceRegistry.Snapshot>, here: Location?, now: Long): String {
val features = JSONArray()
@@ -100,12 +95,12 @@ object LiveExport {
.put("category", best?.category?.name ?: JSONObject.NULL)
.put("confidence", best?.confidence ?: 0)
.put("rssi", s.rssi)
- .put("last_seen", iso.format(Date(s.lastSeen)))))
+ .put("last_seen", ExportText.iso(s.lastSeen))))
}
if (here != null) features.put(JSONObject()
.put("type", "Feature")
.put("geometry", JSONObject().put("type", "Point").put("coordinates", JSONArray().put(here.longitude).put(here.latitude)))
- .put("properties", JSONObject().put("name", "You (RF Sentinel)").put("updated", iso.format(Date(now)))))
+ .put("properties", JSONObject().put("name", "You (RF Sentinel)").put("updated", ExportText.iso(now))))
return JSONObject().put("type", "FeatureCollection").put("features", features).toString()
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
index dcbe9f3..d33d4a6 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
@@ -349,9 +349,6 @@ object Prefs {
* Map device filter (a [com.rfsentinel.app.ui.DeviceFilter] name). Older
* versions had only "all devices" on/off: off becomes Flagged.
*/
- /** The live map's last zoom. A zoom level is not a place, so it is always kept. */
- fun mapZoom(context: Context): Double? = sp(context).getFloat("map_zoom", -1f).takeIf { it > 0f }?.toDouble()
-
/** Where the live map last looked; remembered only with GPS tagging on, like the other saved positions. */
fun lastMapCenter(context: Context): Pair<Double, Double>? {
if (!gpsTaggingEnabled(context)) return null
diff --git a/app/src/main/java/com/rfsentinel/app/util/TripExport.kt b/app/src/main/java/com/rfsentinel/app/util/TripExport.kt
index 43ec416..5c531dd 100644
--- a/app/src/main/java/com/rfsentinel/app/util/TripExport.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/TripExport.kt
@@ -8,10 +8,9 @@ import com.rfsentinel.app.data.TripEntity
import com.rfsentinel.app.data.TripPingEntity
import com.rfsentinel.app.data.TripPointEntity
import com.rfsentinel.app.detect.DeviceIntel
-import java.text.SimpleDateFormat
-import java.util.Date
+import com.rfsentinel.app.util.ExportText.iso
+import com.rfsentinel.app.util.ExportText.local
import java.util.Locale
-import java.util.TimeZone
/**
* Exports a recorded trace: your GPS track plus the devices heard along it
@@ -20,9 +19,6 @@ import java.util.TimeZone
*/
object TripExport {
- private fun iso(t: Long): String =
- SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC") }.format(Date(t))
- private fun local(t: Long): String = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date(t))
private fun x(s: String?): String = ExportText.xml(s)
private fun q(s: String?): String = ExportText.csv(s)
diff --git a/app/src/main/proto/waze.proto b/app/src/main/proto/waze.proto
index f6585c8..91cd397 100644
--- a/app/src/main/proto/waze.proto
+++ b/app/src/main/proto/waze.proto
@@ -1,6 +1,6 @@
// Vendored from highway-radar-sabre-plus (MIT, (c) 2026 highway-radar-sabre-plus
// contributors) — see app/src/main/java/com/rfsentinel/app/online/wazert/LICENSE.
-// Unmodified except for java_package, which points at RF Sentinel's own package.
+// Adapted for RF Sentinel's read-only fetch path and Java package.
//
// Minimal, wire-compatible description of the Waze mobile RT protocol, limited
// to the messages this plugin exchanges. Field numbers and wire types match
@@ -49,8 +49,7 @@ message Element {
optional LoginSuccessful login_successful = 2225;
optional AT at = 2384;
optional AddAlertAction add_alert_action = 2708;
- optional AddUserReportedAlertRequest add_user_reported_alert_request = 2737;
- optional AddUserReportedAlertResponse add_user_reported_alert_response = 2738;
+ reserved 2737, 2738; // Alert submission is not part of this read-only client.
optional LoginRequest login_request = 2744;
optional LoginResponse login_response = 2745;
}
@@ -465,119 +464,3 @@ message ServerError {
message ResponseTimestamp {}
message LoginSuccessful {}
message AT {}
-
-// ---------------------------------------------------------------------------
-// Alert REPORTING (write) path (plain int32/int64/enum/double/message, no
-// zig-zag). Built by WazeReportCodec.
-// ---------------------------------------------------------------------------
-
-message CoordinateWithAlt {
- optional int32 lon_times1000000 = 101;
- optional int32 lat_times1000000 = 102;
- optional int32 alt_times1000000 = 103;
-}
-
-message SegmentNodes {
- optional int64 from_node = 1;
- optional int64 to_node = 2;
-}
-
-message GpsPosition {
- optional CoordinateWithAlt coordinate = 1;
- optional double horizontal_accuracy_meters = 2;
- optional int64 time_epoch_ms = 3;
-}
-
-message UserPosition {
- optional GpsPosition gps_position = 1;
- optional SegmentNodes segment_nodes = 2;
-}
-
-message Timestamp {
- optional int64 seconds = 1;
- optional int32 nanos = 2;
-}
-
-enum ReportingManner {
- REPORTING_MANNER_UNSPECIFIED = 0;
- REPORTING_MANNER_DEFAULT = 1;
- REPORTING_MANNER_VOICE = 2;
- REPORTING_MANNER_VOICE_CONVERSATION = 3;
-}
-
-enum PoliceAlertSubType {
- POLICE_UNSPECIFIED = 0;
- POLICE_DEFAULT = 1;
- POLICE_HIDDEN_REPORT = 2;
- POLICE_MOBILE_CAMERA = 3;
-}
-message PoliceDetails { optional PoliceAlertSubType type = 1; }
-
-enum CrashReportSubType {
- CRASH_REPORT_UNSPECIFIED = 0;
- CRASH_REPORT_DEFAULT = 1;
- CRASH_REPORT_PILE_UP = 2;
- CRASH_REPORT_MAJOR = 3;
- CRASH_REPORT_MINOR = 4;
-}
-message CrashDetails { optional CrashReportSubType type = 1; }
-
-enum TrafficReportSubType {
- TRAFFIC_REPORT_UNSPECIFIED = 0;
- TRAFFIC_REPORT_DEFAULT = 1;
- TRAFFIC_REPORT_STANDSTILL = 2;
- TRAFFIC_REPORT_LIGHT = 3;
- TRAFFIC_REPORT_MODERATE = 4;
- TRAFFIC_REPORT_HEAVY = 5;
-}
-message TrafficDetails { optional TrafficReportSubType type = 1; }
-
-enum HazardReportSubType {
- HAZARD_REPORT_UNSPECIFIED = 0;
- HAZARD_REPORT_DEFAULT = 1;
- HAZARD_REPORT_CONSTRUCTION = 2;
- HAZARD_REPORT_VEHICLE_STOPPED = 3;
- HAZARD_REPORT_OBJECT_ON_ROAD = 4;
- HAZARD_REPORT_POTHOLE = 5;
- HAZARD_REPORT_BROKEN_TRAFFIC_LIGHT = 6;
- HAZARD_REPORT_OIL = 7;
- HAZARD_REPORT_ANIMALS = 8;
- HAZARD_REPORT_MISSING_SIGN = 9;
- HAZARD_REPORT_ROAD_KILL = 10;
- HAZARD_REPORT_SHOULDER = 11;
- HAZARD_REPORT_SHOULDER_VEHICLE_STOPPED = 12;
- HAZARD_REPORT_EMERGENCY_VEHICLE = 13;
-}
-message HazardOnRoadDetails { optional HazardReportSubType type = 1; }
-
-message AlertDetails {
- oneof details {
- TrafficDetails traffic = 1;
- PoliceDetails police = 2;
- CrashDetails crash = 3;
- HazardOnRoadDetails hazard_on_road = 4;
- }
-}
-
-message AddUserReportedAlertRequest {
- optional UserPosition user_position = 1;
- optional int32 azymuth = 2;
- optional AlertDetails alert_details = 3;
- optional SegmentDirection segment_direction = 4;
- optional Timestamp report_time = 5;
- optional bool is_offline_delayed_report = 6;
- optional ReportingManner reporting_manner = 7;
-}
-
-message AddUserReportedAlertResponse {
- enum AddAlertStatus {
- STATUS_UNSPECIFIED = 0;
- SUCCESS = 1;
- FAILURE = 2;
- }
- optional AddAlertStatus status = 1;
- optional int32 received_points_count = 2;
- optional int64 client_alert_id = 3;
- optional AlertDetails alert_details = 4;
- optional string alert_uuid = 5;
-}
diff --git a/app/src/main/res/drawable/ic_car_list.xml b/app/src/main/res/drawable/ic_car_list.xml
deleted file mode 100644
index 698c78b..0000000
--- a/app/src/main/res/drawable/ic_car_list.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Material Design icon (Apache-2.0), used on the Android Auto screens. -->
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
- android:width="24dp"
- android:height="24dp"
- android:viewportWidth="24"
- android:viewportHeight="24">
- <path
- android:fillColor="#FFFFFF"
- android:pathData="M3,13h2v-2H3v2zM3,17h2v-2H3v2zM3,9h2V7H3v2zM7,13h14v-2H7v2zM7,17h14v-2H7v2zM7,7v2h14V7H7z" />
-</vector>
diff --git a/app/src/main/res/layout/activity_device_history.xml b/app/src/main/res/layout/activity_device_history.xml
deleted file mode 100644
index 79b39d7..0000000
--- a/app/src/main/res/layout/activity_device_history.xml
+++ /dev/null
@@ -1,73 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:paddingStart="16dp"
- android:paddingTop="8dp"
- android:paddingEnd="16dp">
-
- <!-- MAC, name, vendor, type or your note. -->
- <com.google.android.material.textfield.TextInputLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:hint="Search MAC, name, vendor, type, note"
- app:endIconMode="clear_text"
- app:startIconDrawable="@drawable/ic_search">
-
- <com.google.android.material.textfield.TextInputEditText
- android:id="@+id/searchInput"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:imeOptions="actionSearch"
- android:importantForAutofill="no"
- android:inputType="text"
- android:maxLines="1" />
- </com.google.android.material.textfield.TextInputLayout>
-
- <HorizontalScrollView
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:scrollbars="none">
-
- <com.google.android.material.chip.ChipGroup
- android:id="@+id/filterChips"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- app:selectionRequired="true"
- app:singleLine="true"
- app:singleSelection="true" />
- </HorizontalScrollView>
-
- <FrameLayout
- android:layout_width="match_parent"
- android:layout_height="0dp"
- android:layout_weight="1">
-
- <androidx.recyclerview.widget.RecyclerView
- android:id="@+id/recyclerView"
- android:layout_width="match_parent"
- android:layout_height="match_parent" />
-
- <TextView
- android:id="@+id/emptyText"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_gravity="center"
- android:gravity="center"
- android:padding="24dp"
- android:textColor="?android:attr/textColorSecondary"
- android:visibility="gone" />
- </FrameLayout>
-
- <!-- How long history is kept (Settings > Data). -->
- <TextView
- android:id="@+id/keptText"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingTop="6dp"
- android:paddingBottom="8dp"
- android:textColor="?android:attr/textColorSecondary"
- android:textSize="@dimen/text_caption" />
-</LinearLayout>
diff --git a/app/src/main/res/layout/activity_log.xml b/app/src/main/res/layout/activity_log.xml
index 1085e4c..cc2c00b 100644
--- a/app/src/main/res/layout/activity_log.xml
+++ b/app/src/main/res/layout/activity_log.xml
@@ -10,6 +10,7 @@
<!-- Address, label, maker, name or evidence. -->
<com.google.android.material.textfield.TextInputLayout
+ android:id="@+id/searchLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search MAC, label, maker, name"
diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml
index 3848013..614888f 100644
--- a/app/src/main/res/layout/activity_main.xml
+++ b/app/src/main/res/layout/activity_main.xml
@@ -101,7 +101,7 @@
android:paddingStart="0dp"
android:paddingEnd="0dp"
app:iconGravity="textStart"
- app:icon="@drawable/ic_car_list"
+ app:icon="@drawable/ic_view_list"
app:iconPadding="0dp" />
<com.google.android.material.button.MaterialButton
diff --git a/app/src/main/res/layout/activity_map.xml b/app/src/main/res/layout/activity_map.xml
index 6b7bedc..f9c6a29 100644
--- a/app/src/main/res/layout/activity_map.xml
+++ b/app/src/main/res/layout/activity_map.xml
@@ -312,79 +312,43 @@
<!-- Where to? Search a destination (Home, Work, starred, recent). -->
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/searchButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="end"
- android:layout_marginEnd="14dp"
- android:layout_marginBottom="8dp"
+ style="@style/MapActionButton"
android:contentDescription="Search a destination"
- android:src="@drawable/ic_search"
- app:fabSize="mini"
- app:tint="#FFFFFF" />
+ android:src="@drawable/ic_search" />
<!-- On the main screen: open the map full screen. -->
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fullscreenButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="end"
- android:layout_marginEnd="14dp"
- android:layout_marginBottom="8dp"
+ style="@style/MapActionButton"
android:contentDescription="Open the map full screen"
android:src="@drawable/ic_fullscreen"
- android:visibility="gone"
- app:fabSize="mini"
- app:tint="#FFFFFF" />
+ android:visibility="gone" />
<!-- Map settings (provider, layers...): Settings > Map. -->
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/mapSettingsButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="end"
- android:layout_marginEnd="14dp"
- android:layout_marginBottom="8dp"
+ style="@style/MapActionButton"
android:contentDescription="Map settings"
- android:src="@drawable/ic_settings"
- app:fabSize="mini"
- app:tint="#FFFFFF" />
+ android:src="@drawable/ic_settings" />
<!-- Light / dark map. -->
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/themeButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="end"
- android:layout_marginEnd="14dp"
- android:layout_marginBottom="8dp"
+ style="@style/MapActionButton"
android:contentDescription="Light / dark map"
- android:src="@drawable/ic_dark_mode"
- app:fabSize="mini"
- app:tint="#FFFFFF" />
+ android:src="@drawable/ic_dark_mode" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/orientationButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="end"
- android:layout_marginEnd="14dp"
- android:layout_marginBottom="8dp"
+ style="@style/MapActionButton"
android:contentDescription="Map: north up"
- android:src="@drawable/ic_north_up"
- app:fabSize="mini"
- app:tint="#FFFFFF" />
+ android:src="@drawable/ic_north_up" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/centerButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="end"
- android:layout_marginEnd="14dp"
- android:layout_marginBottom="8dp"
+ style="@style/MapActionButton"
android:contentDescription="Follow my position"
- android:src="@drawable/ic_my_location"
- app:fabSize="mini"
- app:tint="#FFFFFF" />
+ android:src="@drawable/ic_my_location" />
</LinearLayout>
<!-- A place or the routes to it: pick one and start. -->
diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml
index 8ba3ed8..566e271 100644
--- a/app/src/main/res/layout/activity_settings.xml
+++ b/app/src/main/res/layout/activity_settings.xml
@@ -5,26 +5,22 @@
android:layout_height="match_parent">
<LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
+ style="@style/SettingsControl"
android:orientation="vertical"
android:padding="16dp">
<!-- ================= General ================= -->
<TextView android:id="@+id/headerGeneral" style="@style/SettingsHeader" android:paddingTop="4dp" android:text="General" />
- <LinearLayout android:id="@+id/sectionGeneral" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionGeneral" android:orientation="vertical">
<Button
android:id="@+id/runSetupButton"
- style="@style/Widget.MaterialComponents.Button.OutlinedButton"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
+ style="@style/SettingsOutlinedButton"
android:text="Run the setup wizard again" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/autoUpdateSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Check for updates on app open" />
<com.google.android.material.switchmaterial.SwitchMaterial
@@ -34,50 +30,45 @@
android:text="Include prerelease builds" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/discreetSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Discreet mode" />
<TextView android:id="@+id/screenLabel" style="@style/SettingsLabel" android:text="Screen while the app is open" />
<RadioGroup
- android:id="@+id/screenModeGroup"
- android:layout_width="match_parent"
- android:layout_height="wrap_content">
+ style="@style/SettingsControl"
+ android:id="@+id/screenModeGroup">
- <RadioButton android:id="@+id/screenAlwaysOn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Always on" />
- <RadioButton android:id="@+id/screenOnCharging" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="On while charging" />
- <RadioButton android:id="@+id/screenNormal" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Normal" />
+ <RadioButton style="@style/SettingsControl" android:id="@+id/screenAlwaysOn" android:text="Always on" />
+ <RadioButton style="@style/SettingsControl" android:id="@+id/screenOnCharging" android:text="On while charging" />
+ <RadioButton style="@style/SettingsControl" android:id="@+id/screenNormal" android:text="Normal" />
</RadioGroup>
<TextView android:id="@+id/rotationLabel" style="@style/SettingsLabel" android:text="Screen rotation" />
<RadioGroup
- android:id="@+id/rotationGroup"
- android:layout_width="match_parent"
- android:layout_height="wrap_content">
+ style="@style/SettingsControl"
+ android:id="@+id/rotationGroup">
- <RadioButton android:id="@+id/rotationNormal" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Normal" />
- <RadioButton android:id="@+id/rotationAllWays" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Auto-rotate, upside down too" />
- <RadioButton android:id="@+id/rotationUpsideDown" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Always upside down" />
+ <RadioButton style="@style/SettingsControl" android:id="@+id/rotationNormal" android:text="Normal" />
+ <RadioButton style="@style/SettingsControl" android:id="@+id/rotationAllWays" android:text="Auto-rotate, upside down too" />
+ <RadioButton style="@style/SettingsControl" android:id="@+id/rotationUpsideDown" android:text="Always upside down" />
</RadioGroup>
</LinearLayout>
<!-- ================= Appearance ================= -->
<TextView android:id="@+id/headerAppearance" style="@style/SettingsHeader" android:text="Appearance" />
- <LinearLayout android:id="@+id/sectionAppearance" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionAppearance" android:orientation="vertical">
<RadioGroup
- android:id="@+id/themeGroup"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
+ style="@style/SettingsControl"
+ android:id="@+id/themeGroup" />
<TextView android:id="@+id/bannerLabel" style="@style/SettingsLabel" android:text="Banner image" />
<LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
+ style="@style/SettingsControl"
android:orientation="horizontal">
<Button
@@ -101,44 +92,39 @@
<!-- ================= Scanning ================= -->
<TextView android:id="@+id/headerScanning" style="@style/SettingsHeader" android:text="Scanning" />
- <LinearLayout android:id="@+id/sectionScanning" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionScanning" android:orientation="vertical">
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/hideTrustedSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Hide trusted devices" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/bleSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Bluetooth scanning" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/wifiSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="WiFi scanning" />
<TextView android:id="@+id/scanModeLabel" style="@style/SettingsLabel" android:text="Bluetooth scan intensity" />
<RadioGroup
- android:id="@+id/scanModeGroup"
- android:layout_width="match_parent"
- android:layout_height="wrap_content">
+ style="@style/SettingsControl"
+ android:id="@+id/scanModeGroup">
- <RadioButton android:id="@+id/scanModeLowLatency" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Maximum" />
- <RadioButton android:id="@+id/scanModeBalanced" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Balanced" />
- <RadioButton android:id="@+id/scanModeLowPower" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Battery saver" />
+ <RadioButton style="@style/SettingsControl" android:id="@+id/scanModeLowLatency" android:text="Maximum" />
+ <RadioButton style="@style/SettingsControl" android:id="@+id/scanModeBalanced" android:text="Balanced" />
+ <RadioButton style="@style/SettingsControl" android:id="@+id/scanModeLowPower" android:text="Battery saver" />
</RadioGroup>
<TextView android:id="@+id/intervalLabel" style="@style/SettingsLabel" android:text="WiFi scan interval" />
<EditText
+ style="@style/SettingsControl"
android:id="@+id/intervalInput"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:hint="30"
android:importantForAutofill="no"
android:inputType="number" />
@@ -151,33 +137,27 @@
<Button
android:id="@+id/wifiThrottleButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Open Developer options" />
<Button
android:id="@+id/batteryButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Allow background scanning" />
</LinearLayout>
<!-- ================= Auto-start ================= -->
<TextView android:id="@+id/headerAutoStart" style="@style/SettingsHeader" android:text="Auto-start" />
- <LinearLayout android:id="@+id/sectionAutoStart" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionAutoStart" android:orientation="vertical">
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/bootSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="When the phone starts" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/carAutoSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="In the car" />
<com.google.android.material.switchmaterial.SwitchMaterial
@@ -200,9 +180,7 @@
<Button
android:id="@+id/carDevicesButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Choose your car's Bluetooth" />
<Button
@@ -215,47 +193,44 @@
<!-- ================= What to detect ================= -->
<TextView android:id="@+id/headerDetect" style="@style/SettingsHeader" android:text="What to detect" />
- <LinearLayout android:id="@+id/sectionDetect" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionDetect" android:orientation="vertical">
<LinearLayout
+ style="@style/SettingsControl"
android:id="@+id/categoryContainer"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:orientation="vertical" />
<TextView android:id="@+id/presetLabel" style="@style/SettingsLabel" android:text="Watchlist presets" />
- <CheckBox android:id="@+id/presetGlobal" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Global" />
- <CheckBox android:id="@+id/presetCanada" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Canada" />
- <CheckBox android:id="@+id/presetUs" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="United States" />
- <CheckBox android:id="@+id/presetFrance" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="France" />
- <CheckBox android:id="@+id/presetUk" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="United Kingdom" />
- <CheckBox android:id="@+id/presetPortugal" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Portugal" />
- <CheckBox android:id="@+id/presetGermany" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Germany" />
- <CheckBox android:id="@+id/presetSpain" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Spain" />
- <CheckBox android:id="@+id/presetItaly" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Italy" />
+ <CheckBox style="@style/SettingsControl" android:id="@+id/presetGlobal" android:text="Global" />
+ <CheckBox style="@style/SettingsControl" android:id="@+id/presetCanada" android:text="Canada" />
+ <CheckBox style="@style/SettingsControl" android:id="@+id/presetUs" android:text="United States" />
+ <CheckBox style="@style/SettingsControl" android:id="@+id/presetFrance" android:text="France" />
+ <CheckBox style="@style/SettingsControl" android:id="@+id/presetUk" android:text="United Kingdom" />
+ <CheckBox style="@style/SettingsControl" android:id="@+id/presetPortugal" android:text="Portugal" />
+ <CheckBox style="@style/SettingsControl" android:id="@+id/presetGermany" android:text="Germany" />
+ <CheckBox style="@style/SettingsControl" android:id="@+id/presetSpain" android:text="Spain" />
+ <CheckBox style="@style/SettingsControl" android:id="@+id/presetItaly" android:text="Italy" />
</LinearLayout>
<!-- ================= Alerts ================= -->
<TextView android:id="@+id/headerAlerts" style="@style/SettingsHeader" android:text="Alerts" />
- <LinearLayout android:id="@+id/sectionAlerts" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionAlerts" android:orientation="vertical">
<TextView android:id="@+id/thresholdLabel" style="@style/SettingsLabel" android:text="Alert for matches that are at least" />
<RadioGroup
- android:id="@+id/thresholdGroup"
- android:layout_width="match_parent"
- android:layout_height="wrap_content">
+ style="@style/SettingsControl"
+ android:id="@+id/thresholdGroup">
- <RadioButton android:id="@+id/thresholdWeak" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Weak" />
- <RadioButton android:id="@+id/thresholdMedium" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Probable" />
- <RadioButton android:id="@+id/thresholdStrong" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Strong only" />
+ <RadioButton style="@style/SettingsControl" android:id="@+id/thresholdWeak" android:text="Weak" />
+ <RadioButton style="@style/SettingsControl" android:id="@+id/thresholdMedium" android:text="Probable" />
+ <RadioButton style="@style/SettingsControl" android:id="@+id/thresholdStrong" android:text="Strong only" />
</RadioGroup>
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/soundSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Alert sound" />
<TextView android:id="@+id/alertVolumeLabel" style="@style/SettingsLabel" android:text="Alert volume" />
@@ -273,27 +248,23 @@
</RadioGroup>
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/vibrateSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Vibration" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/radarBeepSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Radar-detector beeps" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/detectorSoundSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Radar-detector sound" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/startupSweepSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:paddingStart="24dp"
android:text="Start beep when a scan starts" />
@@ -306,30 +277,24 @@
<Button
android:id="@+id/detectorEffectButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Detector sound effect" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/scanIntroSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Intro sound when a scan starts" />
<Button
android:id="@+id/testIntroButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Test intro" />
<TextView android:id="@+id/dedupeLabel" style="@style/SettingsLabel" android:text="Re-alert the same device after" />
<EditText
+ style="@style/SettingsControl"
android:id="@+id/dedupeInput"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:hint="5"
android:importantForAutofill="no"
android:inputType="number" />
@@ -337,26 +302,23 @@
<!-- ================= Voice ================= -->
<TextView android:id="@+id/headerVoice" style="@style/SettingsHeader" android:text="Voice" />
- <LinearLayout android:id="@+id/sectionVoice" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionVoice" android:orientation="vertical">
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/voiceSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Spoken alerts" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/shortVoiceSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Short spoken alerts" />
<TextView style="@style/SettingsLabel" android:text="Voice speed" />
<RadioGroup
+ style="@style/SettingsControl"
android:id="@+id/voiceRateGroup"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton android:id="@+id/voiceRateSlow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Slow" />
@@ -367,9 +329,8 @@
<TextView android:id="@+id/voiceBoostLabel" style="@style/SettingsLabel" android:text="Voice loudness" />
<com.google.android.material.slider.Slider
+ style="@style/SettingsControl"
android:id="@+id/voiceBoostSlider"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:contentDescription="Extra loudness for spoken alerts, in decibels"
android:stepSize="1"
android:value="6"
@@ -377,28 +338,22 @@
android:valueTo="15" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/voicePauseMusicSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Pause music while an alert is spoken" />
<LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
+ style="@style/SettingsControl"
android:orientation="horizontal">
<Button
android:id="@+id/voicePickButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Choose voice" />
<Button
android:id="@+id/voiceTestButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Test voice" />
</LinearLayout>
@@ -411,34 +366,30 @@
<!-- ================= Over other apps ================= -->
<TextView android:id="@+id/headerOverlay" style="@style/SettingsHeader" android:text="Over other apps" />
- <LinearLayout android:id="@+id/sectionOverlay" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionOverlay" android:orientation="vertical">
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/bubbleSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Floating threat bubble" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/floatingMapSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Floating mini map" />
</LinearLayout>
<!-- ================= Trackers & followers ================= -->
<TextView android:id="@+id/headerFollow" style="@style/SettingsHeader" android:text="Trackers &amp; followers" />
- <LinearLayout android:id="@+id/sectionFollow" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionFollow" android:orientation="vertical">
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/followSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Warn when a device moves with me" />
<LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
+ style="@style/SettingsControl"
android:orientation="horizontal">
<LinearLayout
@@ -451,9 +402,8 @@
<TextView style="@style/SettingsLabel" android:text="For at least" />
<EditText
+ style="@style/SettingsControl"
android:id="@+id/followMinutesInput"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:importantForAutofill="no"
android:inputType="number" />
</LinearLayout>
@@ -467,9 +417,8 @@
<TextView style="@style/SettingsLabel" android:text="Over" />
<EditText
+ style="@style/SettingsControl"
android:id="@+id/followMetersInput"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:importantForAutofill="no"
android:inputType="number" />
</LinearLayout>
@@ -483,15 +432,13 @@
<Button
android:id="@+id/trackerIgnoreButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Clear ignored trackers" />
</LinearLayout>
<!-- ================= Navigation ================= -->
<TextView android:id="@+id/headerNav" style="@style/SettingsHeader" android:text="Navigation" />
- <LinearLayout android:id="@+id/sectionNav" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" />
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionNav" android:orientation="vertical" />
<!-- ================= Radar ================= -->
<TextView android:id="@+id/headerRadar" style="@style/SettingsHeader" android:text="Radar" />
@@ -534,14 +481,13 @@
<!-- ================= Known cameras ================= -->
<TextView android:id="@+id/headerMap" style="@style/SettingsHeader" android:text="Map" />
- <LinearLayout android:id="@+id/sectionMap" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionMap" android:orientation="vertical">
<TextView android:id="@+id/mapZoomText" style="@style/SettingsLabel" android:text="Default zoom" />
<com.google.android.material.slider.Slider
+ style="@style/SettingsControl"
android:id="@+id/mapZoomSlider"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:contentDescription="Default map zoom"
android:stepSize="1"
android:value="68"
@@ -550,17 +496,14 @@
<Button
android:id="@+id/mapZoomReset"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Waze-like zoom" />
<TextView android:id="@+id/map3dTiltText" style="@style/SettingsLabel" android:text="3D view angle" />
<com.google.android.material.slider.Slider
+ style="@style/SettingsControl"
android:id="@+id/map3dTiltSlider"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:contentDescription="3D driving view angle in degrees"
android:stepSize="5"
android:value="50"
@@ -586,80 +529,67 @@
android:text="OpenFreeMap" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/mapKnownCamerasSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Show plate, speed and red-light cameras" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/mapAutoRecenterSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Auto-recenter" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/mapSpeedometerSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Speedometer" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/mapSpeedLimitLiveSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Speed limit without a route" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/mapTowersSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Show cell towers" />
<LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
+ style="@style/SettingsControl"
android:orientation="horizontal">
<Button
android:id="@+id/mapTracesButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Recorded traces" />
</LinearLayout>
</LinearLayout>
<TextView android:id="@+id/headerCameras" style="@style/SettingsHeader" android:text="Known cameras" />
- <LinearLayout android:id="@+id/sectionCameras" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionCameras" android:orientation="vertical">
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/knownAlprSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Warn before plate-reader cameras" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/speedCameraSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Warn before speed / red-light cameras" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/autoCamerasSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Download cameras for the map area" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/mapCctvSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Show CCTV cameras" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/mapCctvPrivateSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:paddingStart="24dp"
android:text="Include private and indoor CCTV" />
@@ -670,9 +600,8 @@
android:text="Download radius: 100 km" />
<com.google.android.material.slider.Slider
+ style="@style/SettingsControl"
android:id="@+id/cameraRadiusSlider"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:contentDescription="Camera download radius in kilometres"
android:stepSize="10"
android:value="100"
@@ -681,16 +610,12 @@
<Button
android:id="@+id/prefetchCamerasButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Download cameras around me" />
<Button
android:id="@+id/mapDeleteCamerasButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Delete downloaded cameras" />
<TextView
@@ -701,9 +626,7 @@
<Button
android:id="@+id/deflockButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="US &amp; Canada plate cameras · 18 MB" />
<TextView
@@ -721,44 +644,37 @@
<Button
android:id="@+id/ignoredCamerasButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Alert for all ignored cameras again" />
</LinearLayout>
<!-- ================= Cell network ================= -->
<TextView android:id="@+id/headerCell" style="@style/SettingsHeader" android:text="Cell network" />
- <LinearLayout android:id="@+id/sectionCell" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionCell" android:orientation="vertical">
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/cellChangeSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Alert when the cell tower changes" />
<TextView android:id="@+id/disable2gLabel" style="@style/SettingsLabel" android:text="Turn off 2G" />
<Button
android:id="@+id/disable2gButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Open SIM settings" />
<TextView android:id="@+id/cellSecurityLabel" style="@style/SettingsLabel" android:text="Network security alerts" />
<Button
android:id="@+id/cellSecurityButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Open cellular security settings" />
</LinearLayout>
<!-- ================= External hardware ================= -->
<TextView android:id="@+id/headerHardware" style="@style/SettingsHeader" android:text="External hardware" />
- <LinearLayout android:id="@+id/sectionHardware" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionHardware" android:orientation="vertical">
<TextView
android:id="@+id/espStatusText"
@@ -783,9 +699,7 @@
<Button
android:id="@+id/usbWifiLogButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Export USB adapter log" />
<TextView
@@ -795,22 +709,17 @@
android:text="Record what the USB WiFi adapter or V2X board hears, for Wireshark" />
<LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
+ style="@style/SettingsControl"
android:orientation="horizontal">
<Button
android:id="@+id/pcapButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Record frames" />
<Button
android:id="@+id/pcapShareButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:visibility="gone"
android:text="Share last recording" />
</LinearLayout>
@@ -827,15 +736,12 @@
<Button
android:id="@+id/ouiSpyButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Pair OUI-SPY board" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/ouiSpyRelaySwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="OUI-SPY: relay everything" />
<Button
@@ -864,15 +770,13 @@
</RadioGroup>
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/rtl5gSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="AWUS036ACS: also scan 5 GHz" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/usbLightSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="AWUS036ACS: light blinks with traffic" />
</LinearLayout>
@@ -895,16 +799,15 @@
<!-- ================= RTL-SDR radio (filled in by SettingsActivity.setupRadioSection) ================= -->
<TextView android:id="@+id/headerRadio" style="@style/SettingsHeader" android:text="RTL-SDR radio" />
- <LinearLayout android:id="@+id/sectionRadio" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" />
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionRadio" android:orientation="vertical" />
<!-- ================= Location & traces ================= -->
<TextView android:id="@+id/headerLocation" style="@style/SettingsHeader" android:text="Location &amp; traces" />
- <LinearLayout android:id="@+id/sectionLocation" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionLocation" android:orientation="vertical">
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/autoRecordSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Record a trace whenever scanning starts" />
<com.google.android.material.switchmaterial.SwitchMaterial
@@ -914,15 +817,13 @@
android:text="Log every sighting in traces" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/gpsSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Save GPS position with matches" />
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/pinpointSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Pinpoint flagged devices on the map" />
<com.google.android.material.switchmaterial.SwitchMaterial
@@ -934,19 +835,16 @@
<!-- ================= Data ================= -->
<TextView android:id="@+id/headerData" style="@style/SettingsHeader" android:text="Data" />
- <LinearLayout android:id="@+id/sectionData" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionData" android:orientation="vertical">
<com.google.android.material.switchmaterial.SwitchMaterial
+ style="@style/SettingsControl"
android:id="@+id/liveExportSwitch"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:text="Live export for other mapping apps" />
<Button
android:id="@+id/liveExportFolderButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Choose folder" />
<TextView
@@ -958,76 +856,59 @@
<TextView android:id="@+id/retentionLabel" style="@style/SettingsLabel" android:text="Keep history for" />
<EditText
+ style="@style/SettingsControl"
android:id="@+id/retentionInput"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
android:hint="90"
android:importantForAutofill="no"
android:inputType="number" />
<Button
android:id="@+id/importHistoryButton"
- style="@style/Widget.MaterialComponents.Button.OutlinedButton"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
+ style="@style/SettingsOutlinedButton"
android:layout_marginTop="8dp"
android:text="Import device history from a file" />
<Button
android:id="@+id/backupSettingsButton"
- style="@style/Widget.MaterialComponents.Button.OutlinedButton"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
+ style="@style/SettingsOutlinedButton"
android:layout_marginTop="8dp"
android:text="Back up settings to a file" />
<Button
android:id="@+id/restoreSettingsButton"
- style="@style/Widget.MaterialComponents.Button.OutlinedButton"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
+ style="@style/SettingsOutlinedButton"
android:text="Restore settings from a file" />
<Button
android:id="@+id/exportAllButton"
- style="@style/Widget.MaterialComponents.Button.OutlinedButton"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
+ style="@style/SettingsOutlinedButton"
android:layout_marginTop="8dp"
android:text="Export all devices" />
<Button
android:id="@+id/forgetHistoryButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Forget device history" />
<Button
android:id="@+id/clearLogButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Clear match history" />
</LinearLayout>
<!-- ================= Lists, tools & about ================= -->
<TextView android:id="@+id/headerMore" style="@style/SettingsHeader" android:text="Lists, tools &amp; about" />
- <LinearLayout android:id="@+id/sectionMore" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
+ <LinearLayout style="@style/SettingsControl" android:id="@+id/sectionMore" android:orientation="vertical">
<Button
android:id="@+id/openWatchlistButton"
- style="@style/Widget.MaterialComponents.Button.OutlinedButton"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
+ style="@style/SettingsOutlinedButton"
android:layout_marginTop="8dp"
android:text="Watchlist &amp; rules" />
<Button
android:id="@+id/openWhitelistButton"
- style="@style/Widget.MaterialComponents.Button.OutlinedButton"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
+ style="@style/SettingsOutlinedButton"
android:layout_marginTop="8dp"
android:text="Whitelist" />
@@ -1041,33 +922,25 @@
<Button
android:id="@+id/checkUpdateButton"
- style="@style/Widget.MaterialComponents.Button.OutlinedButton"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
+ style="@style/SettingsOutlinedButton"
android:layout_marginTop="8dp"
android:text="Check for updates" />
<Button
android:id="@+id/aboutButton"
- style="@style/Widget.MaterialComponents.Button.OutlinedButton"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
+ style="@style/SettingsOutlinedButton"
android:layout_marginTop="8dp"
android:text="About &amp; sources" />
<Button
android:id="@+id/exportCrashLogButton"
- style="@style/Widget.MaterialComponents.Button.OutlinedButton"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
+ style="@style/SettingsOutlinedButton"
android:layout_marginTop="8dp"
android:text="Export crash log" />
<Button
android:id="@+id/clearCrashLogButton"
- style="@style/Widget.MaterialComponents.Button.TextButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
+ style="@style/SettingsTextButton"
android:text="Clear crash log" />
</LinearLayout>
diff --git a/app/src/main/res/layout/item_device.xml b/app/src/main/res/layout/item_device.xml
index 2348afd..e7663bb 100644
--- a/app/src/main/res/layout/item_device.xml
+++ b/app/src/main/res/layout/item_device.xml
@@ -104,5 +104,6 @@
<View
android:layout_width="match_parent"
android:layout_height="1dp"
- android:background="#22888888" />
+ android:alpha="0.08"
+ android:background="?attr/colorOnSurface" />
</LinearLayout>
diff --git a/app/src/main/res/layout/view_history_retention.xml b/app/src/main/res/layout/view_history_retention.xml
new file mode 100644
index 0000000..b60c6d3
--- /dev/null
+++ b/app/src/main/res/layout/view_history_retention.xml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<TextView xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/keptText"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:paddingTop="6dp"
+ android:paddingBottom="8dp"
+ android:textColor="?android:attr/textColorSecondary"
+ android:textSize="@dimen/text_caption" />
diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml
index 731eb61..cc96b8b 100644
--- a/app/src/main/res/values/themes.xml
+++ b/app/src/main/res/values/themes.xml
@@ -28,14 +28,7 @@
</style>
<!-- A theme made in the theme maker: Material 3 components; ThemeManager recolours it from the maker's accent (Android 11+). -->
- <style name="Theme.RFSentinel.Custom" parent="Theme.Material3.DayNight">
- <item name="rfAccent">?attr/colorPrimary</item>
- <item name="rfOnAccent">?attr/colorOnPrimary</item>
- <item name="rfScopeColor">?attr/colorPrimary</item>
- <item name="rfScopeTextColor">?attr/colorOnSurfaceVariant</item>
- <item name="rfTraceColor">?attr/colorTertiary</item>
- <item name="actionBarTheme">@style/ThemeOverlay.Material3.ActionBar</item>
- </style>
+ <style name="Theme.RFSentinel.Custom" parent="Theme.RFSentinel.MaterialYou" />
<!-- DedSec-inspired hacktivist poster: black and white with electric blue, monospace. -->
<style name="Theme.RFSentinel.DedSec" parent="Theme.MaterialComponents">
@@ -177,11 +170,17 @@
<item name="android:background">?attr/colorSurface</item>
</style>
- <!-- Night Drive: red-only on black, like a cockpit - protects dark adaptation while driving. -->
- <style name="Theme.RFSentinel.NightDrive" parent="Theme.MaterialComponents">
- <!-- Selected chips / toggles use this theme's own primary colour. -->
+ <style name="Theme.RFSentinel.Styled" parent="Theme.MaterialComponents">
<item name="rfAccent">?attr/colorPrimary</item>
<item name="rfOnAccent">?attr/colorOnPrimary</item>
+ <item name="actionBarStyle">@style/Styled.ActionBar</item>
+ <item name="actionBarTheme">@style/Styled.ActionBarOverlay</item>
+ <item name="alertDialogTheme">@style/Styled.Dialog</item>
+ <item name="materialAlertDialogTheme">@style/Styled.Dialog</item>
+ </style>
+
+ <!-- Night Drive: red-only on black, like a cockpit - protects dark adaptation while driving. -->
+ <style name="Theme.RFSentinel.NightDrive" parent="Theme.RFSentinel.Styled">
<item name="colorPrimary">@color/nd_red</item>
<item name="colorPrimaryVariant">@color/nd_bg</item>
<item name="colorOnPrimary">@color/nd_bg</item>
@@ -200,10 +199,6 @@
<item name="fontFamily">sans-serif-condensed</item>
<item name="android:statusBarColor">@color/nd_bg</item>
<item name="android:navigationBarColor">@color/nd_bg</item>
- <item name="actionBarStyle">@style/Styled.ActionBar</item>
- <item name="actionBarTheme">@style/Styled.ActionBarOverlay</item>
- <item name="alertDialogTheme">@style/Styled.Dialog</item>
- <item name="materialAlertDialogTheme">@style/Styled.Dialog</item>
<item name="rfBarColor">@color/nd_bg</item>
<item name="rfTitleColor">@color/nd_red</item>
<item name="rfScopeColor">@color/nd_deep</item>
@@ -212,10 +207,7 @@
</style>
<!-- Night Vision: green phosphor image-intensifier look. -->
- <style name="Theme.RFSentinel.NightVision" parent="Theme.MaterialComponents">
- <!-- Selected chips / toggles use this theme's own primary colour. -->
- <item name="rfAccent">?attr/colorPrimary</item>
- <item name="rfOnAccent">?attr/colorOnPrimary</item>
+ <style name="Theme.RFSentinel.NightVision" parent="Theme.RFSentinel.Styled">
<item name="colorPrimary">@color/nv_green</item>
<item name="colorPrimaryVariant">@color/nv_bg</item>
<item name="colorOnPrimary">@color/nv_bg</item>
@@ -234,10 +226,6 @@
<item name="fontFamily">@font/share_tech_mono</item>
<item name="android:statusBarColor">@color/nv_bg</item>
<item name="android:navigationBarColor">@color/nv_bg</item>
- <item name="actionBarStyle">@style/Styled.ActionBar</item>
- <item name="actionBarTheme">@style/Styled.ActionBarOverlay</item>
- <item name="alertDialogTheme">@style/Styled.Dialog</item>
- <item name="materialAlertDialogTheme">@style/Styled.Dialog</item>
<item name="rfBarColor">@color/nv_bg</item>
<item name="rfTitleColor">@color/nv_green</item>
<item name="rfScopeColor">@color/nv_green</item>
@@ -246,10 +234,7 @@
</style>
<!-- Amber CRT: 1980s monochrome terminal. -->
- <style name="Theme.RFSentinel.Amber" parent="Theme.MaterialComponents">
- <!-- Selected chips / toggles use this theme's own primary colour. -->
- <item name="rfAccent">?attr/colorPrimary</item>
- <item name="rfOnAccent">?attr/colorOnPrimary</item>
+ <style name="Theme.RFSentinel.Amber" parent="Theme.RFSentinel.Styled">
<item name="colorPrimary">@color/amber_main</item>
<item name="colorPrimaryVariant">@color/amber_bg</item>
<item name="colorOnPrimary">@color/amber_bg</item>
@@ -268,10 +253,6 @@
<item name="fontFamily">monospace</item>
<item name="android:statusBarColor">@color/amber_bg</item>
<item name="android:navigationBarColor">@color/amber_bg</item>
- <item name="actionBarStyle">@style/Styled.ActionBar</item>
- <item name="actionBarTheme">@style/Styled.ActionBarOverlay</item>
- <item name="alertDialogTheme">@style/Styled.Dialog</item>
- <item name="materialAlertDialogTheme">@style/Styled.Dialog</item>
<item name="rfBarColor">@color/amber_bg</item>
<item name="rfTitleColor">@color/amber_main</item>
<item name="rfScopeColor">@color/amber_main</item>
@@ -280,10 +261,7 @@
</style>
<!-- Synthwave: neon pink and cyan over a purple night. -->
- <style name="Theme.RFSentinel.Synthwave" parent="Theme.MaterialComponents">
- <!-- Selected chips / toggles use this theme's own primary colour. -->
- <item name="rfAccent">?attr/colorPrimary</item>
- <item name="rfOnAccent">?attr/colorOnPrimary</item>
+ <style name="Theme.RFSentinel.Synthwave" parent="Theme.RFSentinel.Styled">
<item name="colorPrimary">@color/sw_pink</item>
<item name="colorPrimaryVariant">@color/sw_bg</item>
<item name="colorOnPrimary">@color/sw_bg</item>
@@ -302,10 +280,6 @@
<item name="fontFamily">sans-serif-medium</item>
<item name="android:statusBarColor">@color/sw_bg</item>
<item name="android:navigationBarColor">@color/sw_bg</item>
- <item name="actionBarStyle">@style/Styled.ActionBar</item>
- <item name="actionBarTheme">@style/Styled.ActionBarOverlay</item>
- <item name="alertDialogTheme">@style/Styled.Dialog</item>
- <item name="materialAlertDialogTheme">@style/Styled.Dialog</item>
<item name="rfBarColor">@color/sw_bg</item>
<item name="rfTitleColor">@color/sw_pink</item>
<item name="rfScopeColor">@color/sw_cyan</item>
@@ -314,10 +288,7 @@
</style>
<!-- Tactical: olive drab and coyote tan, low glare. -->
- <style name="Theme.RFSentinel.Tactical" parent="Theme.MaterialComponents">
- <!-- Selected chips / toggles use this theme's own primary colour. -->
- <item name="rfAccent">?attr/colorPrimary</item>
- <item name="rfOnAccent">?attr/colorOnPrimary</item>
+ <style name="Theme.RFSentinel.Tactical" parent="Theme.RFSentinel.Styled">
<item name="colorPrimary">@color/tac_olive</item>
<item name="colorPrimaryVariant">@color/tac_bg</item>
<item name="colorOnPrimary">@color/tac_bg</item>
@@ -336,10 +307,6 @@
<item name="fontFamily">sans-serif-condensed</item>
<item name="android:statusBarColor">@color/tac_panel</item>
<item name="android:navigationBarColor">@color/tac_panel</item>
- <item name="actionBarStyle">@style/Styled.ActionBar</item>
- <item name="actionBarTheme">@style/Styled.ActionBarOverlay</item>
- <item name="alertDialogTheme">@style/Styled.Dialog</item>
- <item name="materialAlertDialogTheme">@style/Styled.Dialog</item>
<item name="rfBarColor">@color/tac_panel</item>
<item name="rfTitleColor">@color/tac_tan</item>
<item name="rfScopeColor">@color/tac_olive</item>
@@ -348,10 +315,7 @@
</style>
<!-- Blueprint: white technical drawing on drafting blue. -->
- <style name="Theme.RFSentinel.Blueprint" parent="Theme.MaterialComponents">
- <!-- Selected chips / toggles use this theme's own primary colour. -->
- <item name="rfAccent">?attr/colorPrimary</item>
- <item name="rfOnAccent">?attr/colorOnPrimary</item>
+ <style name="Theme.RFSentinel.Blueprint" parent="Theme.RFSentinel.Styled">
<item name="colorPrimary">@color/bp_line</item>
<item name="colorPrimaryVariant">@color/bp_bg</item>
<item name="colorOnPrimary">@color/bp_bg</item>
@@ -370,10 +334,6 @@
<item name="fontFamily">serif-monospace</item>
<item name="android:statusBarColor">@color/bp_bg</item>
<item name="android:navigationBarColor">@color/bp_bg</item>
- <item name="actionBarStyle">@style/Styled.ActionBar</item>
- <item name="actionBarTheme">@style/Styled.ActionBarOverlay</item>
- <item name="alertDialogTheme">@style/Styled.Dialog</item>
- <item name="materialAlertDialogTheme">@style/Styled.Dialog</item>
<item name="rfBarColor">@color/bp_bg</item>
<item name="rfTitleColor">@color/bp_line</item>
<item name="rfScopeColor">@color/bp_line</item>
@@ -417,9 +377,32 @@
<item name="rfTraceColor">@color/paper_red</item>
</style>
- <style name="SettingsHeader">
+ <style name="MapActionButton">
+ <item name="android:layout_width">wrap_content</item>
+ <item name="android:layout_height">wrap_content</item>
+ <item name="android:layout_gravity">end</item>
+ <item name="android:layout_marginEnd">14dp</item>
+ <item name="android:layout_marginBottom">8dp</item>
+ <item name="fabSize">mini</item>
+ <item name="tint">#FFFFFF</item>
+ </style>
+
+ <style name="SettingsControl">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
+ </style>
+
+ <style name="SettingsTextButton" parent="Widget.MaterialComponents.Button.TextButton">
+ <item name="android:layout_width">wrap_content</item>
+ <item name="android:layout_height">wrap_content</item>
+ </style>
+
+ <style name="SettingsOutlinedButton" parent="Widget.MaterialComponents.Button.OutlinedButton">
+ <item name="android:layout_width">match_parent</item>
+ <item name="android:layout_height">wrap_content</item>
+ </style>
+
+ <style name="SettingsHeader" parent="SettingsControl">
<item name="android:paddingTop">20dp</item>
<item name="android:paddingBottom">4dp</item>
<item name="android:textSize">16sp</item>
@@ -427,9 +410,7 @@
<item name="android:textColor">?attr/colorSecondary</item>
</style>
- <style name="SettingsLabel">
- <item name="android:layout_width">match_parent</item>
- <item name="android:layout_height">wrap_content</item>
+ <style name="SettingsLabel" parent="SettingsControl">
<item name="android:paddingTop">10dp</item>
<item name="android:textSize">13sp</item>
</style>