RF Sentinel (RFSentinel): free, open-source police detector app for Android. Spots police body cams, Flock ALPR cameras, AirTag trackers, Remote ID drones, smart glasses and fake cell towers from Bluetooth LE and WiFi. No root.
Kotlin airtagalprandroidandroid-autoanti-surveillancebluetooth-low-energybody-cameracounter-surveillancedrone-detectionflock-safetyimsi-catcher-detectorpolice-detectorpolice-scannerprivacyremote-idrtl-sdrsdrsurveillance-detectiontracker-detectionwifi
Watchlist name-prefix rules, bug and memory fixes, UI clean-up
CIS-C0068d042ddce4
diff --git a/README.md b/README.mdindex 5f6997f..f93431b 100644--- a/README.md+++ b/README.md@@ -213,7 +213,7 @@ Everything the app does, grouped by area.- Optional **cell tower layer** (or the map's **Cells** chip): every tower seen while scanning, at the spot where its signal was strongest- **Record traces** of your route and the devices along it, with the screen off (with the network names each device asked for, when a USB adapter or Marauder board is plugged in)- **History map & timeline:** heatmap of where flagged equipment showed up, and when (hour of day, day of week)-- **Device history (search):** every device the app remembers, in range or not, searchable by address (with or without colons), name, vendor, type, your own name for it or your note, filtered to favorites, flagged before or seen today; tap one for its details page. History is kept as long as you set in Settings → Data+- **Device history:** every device the app remembers, in range or not, searchable by address (with or without colons), name, vendor, type, your own name for it or your note, filtered to favorites, flagged before or seen today; tap one for its details page. History is kept as long as you set in Settings → Data</details>@@ -727,7 +727,7 @@ hardware. **Settings → RTL-SDR radio**:stored encrypted; your position rounded to ~1 km is sent, at most once a day perarea). A hit takes the closest name within the set ± kHz.-**Requested networks** (Menu → *Requested networks*): phones and laptops ask by+**Requested networks** (Menu → History → *Requested networks*): phones and laptops ask byname for networks they joined before. With an adapter or a Marauder boardplugged in, RF Sentinel can keep these names (off by default: they're otherpeople's network names; always kept while a map trace records). Tap **Watch** ondiff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.ktindex 76dd9c4..4cb6513 100644--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt@@ -365,6 +365,7 @@ class MainActivity : AppCompatActivity() {chip.chipMinHeight = 32 * dpchip.setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, 14f)chip.chipStartPadding = stock[0]; chip.textStartPadding = stock[1]; chip.textEndPadding = stock[2]; chip.chipEndPadding = stock[3]+ sameSize(chip)return}// Tighter sides, so All, Flagged, Bluetooth, WiFi and Cells with their counts fit a phone's width.@@ -382,6 +383,17 @@ class MainActivity : AppCompatActivity() {chip.setTextColor(android.content.res.ColorStateList(arrayOf(checked, none), intArrayOf(onAccent, c)))chip.chipMinHeight = 28 * dpchip.setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, 13f)+ sameSize(chip)+ }++ /**+ * Every chip the same height, however often it was restyled: Flagged is restyled each time its colour changes,+ * and the touch frame switched on and off on the way left it a different size from the rest.+ */+ private fun sameSize(chip: com.google.android.material.chip.Chip) {+ chip.setEnsureMinTouchTargetSize(false) // no invisible 48 dp frame (see setupFilterChips)+ chip.minHeight = chip.chipMinHeight.toInt()+ chip.requestLayout()}/** List / radar toggle: the selected half filled with the theme highlight. */@@ -535,9 +547,14 @@ class MainActivity : AppCompatActivity() {}}+ /** Where the pill is going (not where it is): a show during the hide's fade must still show it. */+ private var newAlertPillShown = false+private fun showNewAlertPill(show: Boolean) {val pill = binding.newAlertPill- if (show == (pill.visibility == View.VISIBLE)) return+ if (show == newAlertPillShown) return+ newAlertPillShown = show+ pill.animate().cancel()if (show) {val (accent, onAccent) = com.rfsentinel.app.ui.ChipStyle.accent(this)pill.background = android.graphics.drawable.GradientDrawable().apply {diff --git a/app/src/main/java/com/rfsentinel/app/data/Trips.kt b/app/src/main/java/com/rfsentinel/app/data/Trips.ktindex 66d06f0..77780ce 100644--- a/app/src/main/java/com/rfsentinel/app/data/Trips.kt+++ b/app/src/main/java/com/rfsentinel/app/data/Trips.kt@@ -110,6 +110,16 @@ interface TripDao {@Query("SELECT * FROM trip_devices WHERE tripId = :tripId ORDER BY (category IS NULL), confidence DESC, bestRssi DESC")suspend fun devices(tripId: Long): List<TripDeviceEntity>+ /** One device of a trip, read on the caller's (background) thread: a recording trace re-reading one it let go of. */+ @Query("SELECT * FROM trip_devices WHERE tripId = :tripId AND mac = :mac")+ fun deviceNow(tripId: Long, mac: String): TripDeviceEntity?++ @Query("SELECT COUNT(*) FROM trip_devices WHERE tripId = :tripId")+ suspend fun deviceCount(tripId: Long): Int++ @Query("SELECT COUNT(*) FROM trip_devices WHERE tripId = :tripId AND category IS NOT NULL")+ suspend fun flaggedCount(tripId: Long): Int+/** Flagged devices with a position from every recorded trace, for the history map. */@Query("SELECT * FROM trip_devices WHERE category IS NOT NULL AND lat IS NOT NULL AND lastSeen >= :since")suspend fun flaggedDevicesSince(since: Long): List<TripDeviceEntity>diff --git a/app/src/main/java/com/rfsentinel/app/data/WhitelistDao.kt b/app/src/main/java/com/rfsentinel/app/data/WhitelistDao.ktindex 85aff0c..2e00773 100644--- a/app/src/main/java/com/rfsentinel/app/data/WhitelistDao.kt+++ b/app/src/main/java/com/rfsentinel/app/data/WhitelistDao.kt@@ -19,6 +19,9 @@ interface WhitelistDao {@Query("SELECT * FROM whitelist ORDER BY mac ASC")fun all(): Flow<List<WhitelistEntity>>+ @Query("SELECT * FROM whitelist WHERE mac = :mac")+ suspend fun get(mac: String): WhitelistEntity?+@Query("SELECT EXISTS(SELECT 1 FROM whitelist WHERE mac = :mac)")suspend fun isWhitelisted(mac: String): Boolean}diff --git a/app/src/main/java/com/rfsentinel/app/detect/HackerWatch.kt b/app/src/main/java/com/rfsentinel/app/detect/HackerWatch.ktindex 8c04e48..8ad7fac 100644--- a/app/src/main/java/com/rfsentinel/app/detect/HackerWatch.kt+++ b/app/src/main/java/com/rfsentinel/app/detect/HackerWatch.kt@@ -181,6 +181,7 @@ object HackerWatch {val list = bySsid.getOrPut(ssid) { ArrayList() }if (bySsid.size > 400) bySsid.remove(bySsid.keys.first())list.firstOrNull { it.bssid == a.mac }?.let { it.secured = secured; return null }+ if (list.size >= 64) list.removeAt(0) // a hotspot chain ("xfinitywifi") has thousands of access pointsval rogue = list.any { !sameMaker(it.bssid, a.mac) && it.secured != secured }list += Ap(a.mac, secured)if (!rogue || !twinsFlagged.add(ssid + "|" + a.mac)) return nulldiff --git a/app/src/main/java/com/rfsentinel/app/esp/HeardBy.kt b/app/src/main/java/com/rfsentinel/app/esp/HeardBy.ktindex b43f3d3..46bcb56 100644--- a/app/src/main/java/com/rfsentinel/app/esp/HeardBy.kt+++ b/app/src/main/java/com/rfsentinel/app/esp/HeardBy.kt@@ -11,6 +11,8 @@ class RecentMacs {fun mark(mac: String, now: Long = System.currentTimeMillis()) {last[mac.uppercase()] = now+ // A monitor-mode adapter hears thousands of addresses that are never looked up again.+ if (last.size > MAX_MACS) last.entries.removeAll { now - it.value >= HeardBy.WINDOW_MS }}fun recent(mac: String, now: Long = System.currentTimeMillis()): Boolean {@@ -22,6 +24,8 @@ class RecentMacs {}fun clear() = last.clear()++ private companion object { const val MAX_MACS = 5_000 }}object HeardBy {diff --git a/app/src/main/java/com/rfsentinel/app/nav/RenamePlace.kt b/app/src/main/java/com/rfsentinel/app/nav/RenamePlace.ktindex d57645d..d68d757 100644--- a/app/src/main/java/com/rfsentinel/app/nav/RenamePlace.kt+++ b/app/src/main/java/com/rfsentinel/app/nav/RenamePlace.kt@@ -3,7 +3,7 @@ package com.rfsentinel.app.navimport android.content.Contextimport android.widget.EditTextimport android.widget.FrameLayout-import androidx.appcompat.app.AlertDialog+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.util.Prefs/** Asks for a new name for a starred place; [done] gets the renamed place. */@@ -17,7 +17,7 @@ object RenamePlace {val box = FrameLayout(context).apply {val side = (20 * dp).toInt(); setPadding(side, (8 * dp).toInt(), side, 0); addView(input)}- AlertDialog.Builder(context)+ MaterialAlertDialogBuilder(context).setTitle("Rename starred place").setView(box).setPositiveButton("Save") { _, _ ->diff --git a/app/src/main/java/com/rfsentinel/app/online/RoadTiles.kt b/app/src/main/java/com/rfsentinel/app/online/RoadTiles.ktindex c4d8fee..0695f02 100644--- a/app/src/main/java/com/rfsentinel/app/online/RoadTiles.kt+++ b/app/src/main/java/com/rfsentinel/app/online/RoadTiles.kt@@ -179,6 +179,7 @@ object RoadTiles {internal fun clear() = synchronized(memory) { memory.clear() }private fun load(context: Context, t: Tile) {+ if (failedAt.size > 500) failedAt.entries.removeAll { System.currentTimeMillis() - it.value >= 60_000 } // offline all dayval url = tileUrl(context) ?: run { failedAt[t] = System.currentTimeMillis(); return }val version = url.substringAfter("/planet/").substringBefore('/').ifEmpty { "x" }val dir = File(context.cacheDir, "road-tiles/$version")diff --git a/app/src/main/java/com/rfsentinel/app/oui/OuiEntry.kt b/app/src/main/java/com/rfsentinel/app/oui/OuiEntry.ktindex 4c56b10..1398495 100644--- a/app/src/main/java/com/rfsentinel/app/oui/OuiEntry.kt+++ b/app/src/main/java/com/rfsentinel/app/oui/OuiEntry.kt@@ -9,6 +9,8 @@ data class OuiEntry(* - "AA:BB:CC" vendor prefix (IEEE MA-L block)* - "AA:BB:CC:DD:EE:FF" one exact device* - "name:<text>" advertised name / SSID contains <text> (case-insensitive)+ * - "starts:<text>" advertised name / SSID starts with <text> (case-insensitive), e.g. every+ * network named "Flock-..."* - "vendor:<text>" manufacturer (IEEE registrant or Bluetooth company) contains <text>* - "probe:<ssid>" a device asks for this exact WiFi network name (probe request,* heard by a USB WiFi adapter or an ESP32 Marauder board)@@ -28,6 +30,7 @@ data class OuiEntry() {val isCustom get() = confidence == "custom"val isNameRule get() = prefix.startsWith(NAME, ignoreCase = true)+ val isStartsRule get() = prefix.startsWith(STARTS, ignoreCase = true)val isVendorRule get() = prefix.startsWith(VENDOR, ignoreCase = true)val isProbeRule get() = prefix.startsWith(PROBE, ignoreCase = true)val isFingerprintRule get() = prefix.startsWith(FINGERPRINT, ignoreCase = true)@@ -53,6 +56,7 @@ data class OuiEntry(companion object {const val NAME = "name:"+ const val STARTS = "starts:"const val VENDOR = "vendor:"const val PROBE = "probe:"const val FINGERPRINT = "fp:"diff --git a/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.kt b/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.ktindex 5dc22ea..ec4c9b2 100644--- a/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.kt+++ b/app/src/main/java/com/rfsentinel/app/oui/OuiWatchlist.kt@@ -32,6 +32,8 @@ object OuiWatchlist {/** Address entries keyed by hex digits: 12 = one device, 9/7/6 = IEEE block. */val byHex: Map<String, OuiEntry>,val nameRules: List<OuiEntry>,+ /** Name / SSID prefix rules. */+ val startsRules: List<OuiEntry>,val vendorRules: List<OuiEntry>,/** Requested-network rules keyed by the lower-cased network name. */val probeRules: Map<String, OuiEntry>,@@ -53,7 +55,7 @@ object OuiWatchlist {private set@Volatile- private var state = State(emptyMap(), emptyList(), emptyList(), emptyMap(), emptyMap(), emptyList())+ private var state = State(emptyMap(), emptyList(), emptyList(), emptyList(), emptyMap(), emptyMap(), emptyList())/** Load order: regional presets after "global", so their labels win for shared prefixes. */val availablePresets = listOf("global", "canada", "us", "france", "uk", "portugal", "germany", "spain", "italy")@@ -72,8 +74,10 @@ object OuiWatchlist {readCustom(context).forEach { byKey[it.prefix] = it }val all = byKey.values.toList()state = State(- byHex = all.filter { !it.isNameRule && !it.isVendorRule && !it.isProbeRule && !it.isFingerprintRule }.associateBy { MacUtil.hex(it.prefix) },+ byHex = all.filter { !it.isNameRule && !it.isStartsRule && !it.isVendorRule && !it.isProbeRule && !it.isFingerprintRule }+ .associateBy { MacUtil.hex(it.prefix) },nameRules = all.filter { it.isNameRule && it.ruleText.isNotEmpty() },+ startsRules = all.filter { it.isStartsRule && it.ruleText.isNotEmpty() },vendorRules = all.filter { it.isVendorRule && it.ruleText.isNotEmpty() },probeRules = all.filter { it.isProbeRule && it.ruleText.isNotEmpty() }.associateBy { it.ruleText.lowercase() },fingerprintRules = all.filter { it.isFingerprintRule && it.ruleText.isNotEmpty() }.associateBy { it.ruleText.lowercase() },@@ -109,6 +113,7 @@ object OuiWatchlist {val k = key.trim()return when {k.startsWith(OuiEntry.NAME, ignoreCase = true) -> OuiEntry.NAME + k.substringAfter(':').trim()+ k.startsWith(OuiEntry.STARTS, ignoreCase = true) -> OuiEntry.STARTS + k.substringAfter(':').trim()k.startsWith(OuiEntry.VENDOR, ignoreCase = true) -> OuiEntry.VENDOR + k.substringAfter(':').trim()k.startsWith(OuiEntry.PROBE, ignoreCase = true) -> OuiEntry.PROBE + k.substringAfter(':').trim()k.startsWith(OuiEntry.FINGERPRINT, ignoreCase = true) -> OuiEntry.FINGERPRINT + k.substringAfter(':').trim().lowercase()@@ -174,11 +179,11 @@ object OuiWatchlist {fun allEntries(): List<OuiEntry> = state.all- /** Valid keys: IEEE block prefix (24/28/36-bit), full MAC, or a non-empty name:/vendor: rule. */+ /** Valid keys: IEEE block prefix (24/28/36-bit), full MAC, or a non-empty name:/starts:/vendor:/probe:/fp: rule. */fun isValidKey(prefix: String): Boolean {val k = prefix.trim()- if (k.startsWith(OuiEntry.NAME, true) || k.startsWith(OuiEntry.VENDOR, true) || k.startsWith(OuiEntry.PROBE, true) ||- k.startsWith(OuiEntry.FINGERPRINT, true)) {+ if (k.startsWith(OuiEntry.NAME, true) || k.startsWith(OuiEntry.STARTS, true) || k.startsWith(OuiEntry.VENDOR, true) ||+ k.startsWith(OuiEntry.PROBE, true) || k.startsWith(OuiEntry.FINGERPRINT, true)) {return k.substringAfter(':').isNotBlank()}return MacUtil.isValidBlock(k) || MacUtil.isValidMac(k)@@ -210,6 +215,8 @@ object OuiWatchlist {if (name != null) {s.nameRules.filter { name.contains(it.ruleText, ignoreCase = true) }.forEach { out += it.toHit("Name \"$name\" contains \"${it.ruleText}\"") }+ s.startsRules.filter { name.trimStart().startsWith(it.ruleText, ignoreCase = true) }+ .forEach { out += it.toHit("Name \"$name\" starts with \"${it.ruleText}\"") }}if (vendors.isNotEmpty()) {s.vendorRules.forEach { rule ->diff --git a/app/src/main/java/com/rfsentinel/app/ouilist/OuiAdapter.kt b/app/src/main/java/com/rfsentinel/app/ouilist/OuiAdapter.ktindex fd3089a..8ba5e40 100644--- a/app/src/main/java/com/rfsentinel/app/ouilist/OuiAdapter.kt+++ b/app/src/main/java/com/rfsentinel/app/ouilist/OuiAdapter.kt@@ -29,6 +29,7 @@ class OuiAdapter(val item = items[position]holder.binding.prefixText.text = when {item.isNameRule -> "Name contains \"${item.ruleText}\""+ item.isStartsRule -> "Name starts with \"${item.ruleText}\""item.isVendorRule -> "Maker contains \"${item.ruleText}\""item.isProbeRule -> "Asks for network \"${item.ruleText}\""item.isFingerprintRule -> "Probe fingerprint ${item.ruleText}"diff --git a/app/src/main/java/com/rfsentinel/app/ouilist/OuiListActivity.kt b/app/src/main/java/com/rfsentinel/app/ouilist/OuiListActivity.ktindex e60096b..2aa8c8b 100644--- a/app/src/main/java/com/rfsentinel/app/ouilist/OuiListActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ouilist/OuiListActivity.kt@@ -8,7 +8,6 @@ import android.widget.Toastimport androidx.activity.result.contract.ActivityResultContractsimport androidx.appcompat.app.AppCompatActivityimport androidx.recyclerview.widget.LinearLayoutManager-import com.rfsentinel.app.Rimport com.rfsentinel.app.databinding.ActivityOuiListBindingimport com.rfsentinel.app.oui.OuiEntryimport com.rfsentinel.app.oui.OuiWatchlist@@ -20,6 +19,16 @@ class OuiListActivity : AppCompatActivity() {private lateinit var binding: ActivityOuiListBindingprivate lateinit var adapter: OuiAdapter+ /** The kinds of rule the form adds: the dropdown's label, the text box's hint and the key's prefix. */+ private enum class RuleType(val label: String, val hint: String, val keyPrefix: String) {+ ADDRESS("Address or vendor prefix", "Prefix AA:BB:CC or device AA:BB:CC:DD:EE:FF", ""),+ NAME("Name contains", "Text in the device name or WiFi SSID, e.g. Axon", OuiEntry.NAME),+ STARTS("Name starts with", "Start of the device name or WiFi SSID, e.g. Flock-", OuiEntry.STARTS),+ VENDOR("Maker contains", "Text in the manufacturer name, e.g. Motorola", OuiEntry.VENDOR),+ PROBE("Asks for network", "Exact WiFi network name a device asks for", OuiEntry.PROBE)+ }+ private var ruleType = RuleType.ADDRESS+private val importLauncher = registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->if (uri == null) return@registerForActivityResulttry {@@ -43,44 +52,26 @@ class OuiListActivity : AppCompatActivity() {adapter = OuiAdapter(mutableListOf()) { entry ->OuiWatchlist.removeCustomEntry(this, entry.prefix)refresh()+ com.rfsentinel.app.util.Undo.show(this, "Removed ${entry.label}") {+ OuiWatchlist.addCustomEntry(this, entry)+ refresh()+ }}binding.recyclerView.layoutManager = LinearLayoutManager(this)binding.recyclerView.adapter = adapter- binding.ruleType.setOnCheckedChangeListener { _, id ->- when (id) {- R.id.typeName -> {- binding.prefixInput.hint = "Text in the device name / WiFi SSID (e.g. Axon)"- binding.prefixInput.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS- }- R.id.typeVendor -> {- binding.prefixInput.hint = "Text in the manufacturer name (e.g. Motorola)"- binding.prefixInput.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS- }- R.id.typeProbe -> {- binding.prefixInput.hint = "Exact WiFi network name a device asks for"- binding.prefixInput.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS- }- else -> {- binding.prefixInput.hint = "Prefix AA:BB:CC or device AA:BB:CC:DD:EE:FF"- binding.prefixInput.inputType = InputType.TYPE_CLASS_TEXT or- InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS- }- }- }+ val types = RuleType.entries+ binding.ruleType.setAdapter(android.widget.ArrayAdapter(this, android.R.layout.simple_list_item_1, types.map { it.label }))+ binding.ruleType.setOnItemClickListener { _, _, position, _ -> setRuleType(types[position]) }+ setRuleType(savedInstanceState?.getInt(STATE_RULE_TYPE)?.let { types.getOrNull(it) } ?: RuleType.ADDRESS)binding.addButton.setOnClickListener {val text = binding.prefixInput.text.toString().trim()val label = binding.labelInput.text.toString().trim()- val key = when (binding.ruleType.checkedRadioButtonId) {- R.id.typeName -> OuiEntry.NAME + text- R.id.typeVendor -> OuiEntry.VENDOR + text- R.id.typeProbe -> OuiEntry.PROBE + text- else -> text- }+ val key = ruleType.keyPrefix + textif (text.isEmpty() || !OuiWatchlist.isValidKey(key)) {- binding.prefixInput.error = when (binding.ruleType.checkedRadioButtonId) {- R.id.typeAddress -> "Format: AA:BB:CC (vendor) or AA:BB:CC:DD:EE:FF (one device)"+ binding.prefixInput.error = when (ruleType) {+ RuleType.ADDRESS -> "Format: AA:BB:CC for a vendor, AA:BB:CC:DD:EE:FF for one device"else -> "Enter some text to match"}} else if (label.isEmpty()) {@@ -96,9 +87,24 @@ class OuiListActivity : AppCompatActivity() {refresh()}+ /** Shows [type] in the dropdown and sets the text box up for it. */+ private fun setRuleType(type: RuleType) {+ ruleType = type+ binding.ruleType.setText(type.label, false) // false: keep every choice in the list+ binding.prefixInput.hint = type.hint+ binding.prefixInput.error = null+ binding.prefixInput.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or+ (if (type == RuleType.ADDRESS) InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS else 0)+ }++ override fun onSaveInstanceState(outState: Bundle) {+ super.onSaveInstanceState(outState)+ outState.putInt(STATE_RULE_TYPE, ruleType.ordinal)+ }+override fun onCreateOptionsMenu(menu: Menu): Boolean {- menu.add(0, 1, 0, "Export my entries (JSON)")- menu.add(0, 2, 1, "Import entries (JSON)")+ menu.add(0, 1, 0, "Export my entries as JSON")+ menu.add(0, 2, 1, "Import entries from JSON")return true}@@ -116,4 +122,8 @@ class OuiListActivity : AppCompatActivity() {compareByDescending<OuiEntry> { it.isCustom }.thenByDescending { it.effectiveScore }))}++ private companion object {+ const val STATE_RULE_TYPE = "ruleType"+ }}diff --git a/app/src/main/java/com/rfsentinel/app/probes/ProbeListActivity.kt b/app/src/main/java/com/rfsentinel/app/probes/ProbeListActivity.ktindex ae5ece0..3947efd 100644--- a/app/src/main/java/com/rfsentinel/app/probes/ProbeListActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/probes/ProbeListActivity.kt@@ -8,11 +8,11 @@ import android.view.Viewimport android.view.ViewGroupimport android.widget.EditTextimport android.widget.Toast-import androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivityimport androidx.core.widget.doAfterTextChangedimport androidx.recyclerview.widget.LinearLayoutManagerimport androidx.recyclerview.widget.RecyclerView+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.data.ProbeBookimport com.rfsentinel.app.data.ProbeLogimport com.rfsentinel.app.databinding.ActivityProbeListBinding@@ -58,7 +58,7 @@ class ProbeListActivity : AppCompatActivity() {}binding.filterInput.doAfterTextChanged { refresh() }binding.clearButton.setOnClickListener {- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Clear the list?").setMessage("Removes every recorded network name. Watched names stay on the watchlist.").setPositiveButton("Clear") { _, _ -> ProbeLog.clear(this); refresh() }@@ -107,7 +107,7 @@ class ProbeListActivity : AppCompatActivity() {/** Watch [ssid]: the user names what it is; the label is what alerts say. */private fun watch(ssid: String) {val input = EditText(this).apply { setText("Asks for \"$ssid\""); setSelectAllOnFocus(true) }- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Alert when a device asks for \"$ssid\"").setMessage("What is it? This is what the alert says.").setView(input)@@ -122,8 +122,13 @@ class ProbeListActivity : AppCompatActivity() {}private fun unwatch(ssid: String) {+ val entry = OuiWatchlist.customEntry(OuiEntry.PROBE + ssid)OuiWatchlist.removeCustomEntry(this, OuiEntry.PROBE + ssid)refresh()+ if (entry != null) com.rfsentinel.app.util.Undo.show(this, "No longer watching \"$ssid\"") {+ OuiWatchlist.addCustomEntry(this, entry)+ refresh()+ }}private fun details(n: ProbeBook.Network) {@@ -132,7 +137,7 @@ class ProbeListActivity : AppCompatActivity() {mac + " " + (if (MacUtil.isRandomized(mac)) "random address" else VendorDb.macVendor(mac) ?: "unknown maker")}val watched = OuiWatchlist.isProbeWatched(n.ssid)- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle(n.ssid).setMessage("First seen ${df.format(Date(n.firstSeen))}\nLast seen ${df.format(Date(n.lastSeen))}\n\nDevices that asked for it:\n$devices").setPositiveButton(if (watched) "Stop watching" else "Watch") { _, _ -> if (watched) unwatch(n.ssid) else watch(n.ssid) }diff --git a/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt b/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.ktindex 4517d0c..e48012c 100644--- a/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt+++ b/app/src/main/java/com/rfsentinel/app/service/DeviceRegistry.kt@@ -92,6 +92,8 @@ object DeviceRegistry {}private class Track(val mac: String, now: Long) {+ /** Set (atomically with the lookup) by every [report], so pruning can't drop a track that is being updated. */+ @Volatile var touchedAt = nowval sources = HashSet<Advert.Source>()var advert: Advert? = nullvar name: String? = null@@ -156,7 +158,7 @@ object DeviceRegistry {broadcast: GeoSample? = null): Boolean {var isFirst = false- val t = tracks.computeIfAbsent(a.mac) { isFirst = true; Track(a.mac, now) }+ val t = tracks.compute(a.mac) { _, old -> (old ?: Track(a.mac, now).also { isFirst = true }).also { it.touchedAt = now } }!!if (isFirst) linkRotatedAddress(t, a, now)synchronized(t) {PatrolCluster.roleOf(hits, vendor, a.name)?.let { t.role = it }@@ -354,7 +356,8 @@ object DeviceRegistry {/** Light snapshots for the live list; pruned first. */fun snapshot(now: Long = System.currentTimeMillis()): List<Snapshot> {- tracks.values.removeIf { now - it.lastSeen > PRUNE_AFTER_MS }+ // Per key and atomic with report's lookup: a device heard right now is never dropped mid-update.+ for (mac in tracks.keys) tracks.computeIfPresent(mac) { _, t -> t.takeIf { now - maxOf(t.lastSeen, t.touchedAt) <= PRUNE_AFTER_MS } }return tracks.values.map { t -> synchronized(t) { snap(t, full = false) } }}diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.ktindex 06f0d1b..dc5efd4 100644--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt@@ -101,6 +101,8 @@ class ScanForegroundService : Service() {private const val CELL_REPEAT_MS = 30 * 60_000Lprivate const val PLACING_MAX_AGE_MS = 30_000Lprivate const val ESP_HIT_TTL_MS = 5 * 60_000L+ /** A network fix this soon after a raw GPS fix is ignored. */+ private const val RAW_GPS_PREFERRED_MS = 10_000Lprivate const val PLACING_MAX_ACCURACY_M = 50f/** Pinpointing: precise 1 s fixes for this long after a flagged device was last heard. */private const val LOCATING_HOLD_MS = 120_000L@@ -228,7 +230,14 @@ class ScanForegroundService : Service() {onFix(it)}+ /** When raw GPS last gave a fix (backstop, or a phone without fused location). */+ private var lastRawGpsAt = 0L+private fun onFix(it: Location) {+ // Raw GPS and network run side by side: while GPS gives fixes, the coarser network ones would make the+ // position (and a recorded trace) jump back and forth between the two.+ if (it.provider == LocationManager.GPS_PROVIDER) lastRawGpsAt = System.currentTimeMillis()+ else if (it.provider == LocationManager.NETWORK_PROVIDER && System.currentTimeMillis() - lastRawGpsAt < RAW_GPS_PREFERRED_MS) returnif (it.provider == LocationManager.GPS_PROVIDER && it.hasAccuracy() && it.accuracy <= 50f) {val now = System.currentTimeMillis()if (now - lastGoodGpsAt > GPS_RECONNECT_MS) AlertPlayer.gpsConnected(this)@@ -251,7 +260,7 @@ class ScanForegroundService : Service() {override fun onReceive(context: Context, intent: Intent) {when (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)) {BluetoothAdapter.STATE_ON -> if (Prefs.bleEnabled(context)) startBle()- BluetoothAdapter.STATE_TURNING_OFF, BluetoothAdapter.STATE_OFF -> bleEngine.stop()+ BluetoothAdapter.STATE_TURNING_OFF, BluetoothAdapter.STATE_OFF -> stopBle() // its periodic restart too}}}@@ -431,7 +440,8 @@ class ScanForegroundService : Service() {// ---- Scanning ------------------------------------------------------------ private fun bleWatched() = OuiWatchlist.allEntries().filter { it.isCustom && it.prefix.length == 17 }.map { it.prefix }+ // Exact addresses only: a name rule can be 17 characters long too.+ private fun bleWatched() = OuiWatchlist.allEntries().filter { it.isCustom && com.rfsentinel.app.util.MacUtil.isValidMac(it.prefix) }.map { it.prefix }private fun bleSettingsKey() = "${Prefs.bleScanMode(this)}|${bleWatched()}"/** [bleSettingsKey] of the running scan. */private var bleStartedWith = ""@@ -811,6 +821,7 @@ class ScanForegroundService : Service() {}val nearIds = near.map { it.first.osmId }.toSet()alprLastDistance.keys.retainAll(nearIds)+ alprLastAlert.entries.removeAll { now - it.value >= KNOWN_ALPR_REPEAT_MS } // a long drive passes many camerasfor ((cam, d) in near) {val prev = alprLastDistance.put(cam.osmId, d)// Only once a second fix shows you getting closer: a camera you just passed@@ -931,11 +942,28 @@ class ScanForegroundService : Service() {}// Forget classification cache for devices that left.classified.keys.retainAll(devices.map { it.mac }.toSet())+ pruneTimestamps(System.currentTimeMillis())watchdog()}}}+ /**+ * Drops per-address timestamps old enough to make no difference any more (an entry past its window acts+ * the same as none), so a long scan past thousands of rotating addresses doesn't keep every one of them.+ */+ private fun pruneTimestamps(now: Long) {+ val alertKeep = maxOf(Prefs.dedupeWindowMs(this), RADAR_HOLD_MS)+ lastAlerted.entries.removeAll { now - it.value > alertKeep }+ lastLogged.entries.removeAll { now - it.value >= LOG_THROTTLE_MS }+ lastDroneOverhead.entries.removeAll { now - it.value >= DRONE_OVERHEAD_REPEAT_MS }+ // These two belong to the pipeline thread.+ pipeline.post {+ espHits.entries.removeAll { now - it.value.first >= ESP_HIT_TTL_MS }+ probeHits.entries.removeAll { now - it.value.first >= ESP_HIT_TTL_MS }+ }+ }+// ---- Watchdog ----------------------------------------------------------------@Volatile private var lastBleResultAt = 0L@@ -1078,7 +1106,7 @@ class ScanForegroundService : Service() {val threshold = Prefs.alertThreshold(this)val trend = com.rfsentinel.app.sdr.RadioLog.observe(e, name, Prefs.radioTrendDb(this), now)val cell = e.band.kind == com.rfsentinel.app.sdr.RadioWatch.Kind.CELLULAR_UPLINK- if (trend != null && e.confidence >= threshold && now >= Prefs.alertsSnoozedUntil(this)) {+ if (trend != null && e.confidence >= threshold) {AlertPlayer.callout(this, (if (cell) "Cellular signal " else "Radio ${spokenMhz(e.freqHz)} ") +if (trend == com.rfsentinel.app.sdr.RadioLog.Trend.CLOSER) "getting closer" else "moving away")}@@ -1122,7 +1150,7 @@ class ScanForegroundService : Service() {))}- if (e.confidence >= threshold && now >= Prefs.alertsSnoozedUntil(this)) {+ if (e.confidence >= threshold) {NotificationHelper.sendMapAlert(this, "radio:" + e.freqHz, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java)// Spoken: the frequency (and its name) when that's on, else the short phrase.val spoken = when {@@ -1140,12 +1168,13 @@ class ScanForegroundService : Service() {"%.3f".format(java.util.Locale.US, hz / 1e6).trimEnd('0').trimEnd('.')/** Police aircraft (ADS-B) and Waze reports: internet sources, both off by default. */- private val onlineWatch by lazy {+ private val onlineWatchLazy = lazy {com.rfsentinel.app.online.OnlineWatch(this, serviceScope, { lastLocation ?: lastFix },onCallout = { text -> pipeline.post { AlertPlayer.callout(this, text) } }) { alert ->pipeline.post { onOnlineHit(alert) }}}+ private val onlineWatch by onlineWatchLazyprivate fun onlineActive() = Prefs.categoryEnabled(this, Category.AIRCRAFT) ||(Prefs.categoryEnabled(this, Category.POLICE_REPORT) && Prefs.wazeReady(this))@@ -1171,7 +1200,7 @@ class ScanForegroundService : Service() {)}if (alert.level != com.rfsentinel.app.online.WazePolice.Level.LOG &&- hit.confidence >= Prefs.alertThreshold(this) && now >= Prefs.alertsSnoozedUntil(this)) {+ hit.confidence >= Prefs.alertThreshold(this)) {NotificationHelper.sendMapAlert(this, alert.key, hit, lat = alert.lat, lon = alert.lon, online = alert.key)if (alert.level == com.rfsentinel.app.online.WazePolice.Level.LOUD) {AlertPlayer.play(this, hit.tier, alert.spoken ?: com.rfsentinel.app.util.Spoken.shortWord(hit))@@ -1208,7 +1237,7 @@ class ScanForegroundService : Service() {))}- if (a.confidence >= Prefs.alertThreshold(this) && now >= Prefs.alertsSnoozedUntil(this)) {+ if (a.confidence >= Prefs.alertThreshold(this)) {NotificationHelper.sendMapAlert(this, "gnss:" + a.key, hit, com.rfsentinel.app.ui.GnssActivity::class.java)AlertPlayer.play(this, hit.tier, a.title)}@@ -1270,7 +1299,7 @@ class ScanForegroundService : Service() {))}- if (hit.confidence >= Prefs.alertThreshold(this) && now >= Prefs.alertsSnoozedUntil(this)) {+ if (hit.confidence >= Prefs.alertThreshold(this)) {NotificationHelper.sendMapAlert(this, key, hit, com.rfsentinel.app.ui.DetectionLogActivity::class.java)AlertPlayer.play(this, hit.tier, spoken)}@@ -1399,8 +1428,11 @@ class ScanForegroundService : Service() {com.rfsentinel.app.esp.EspBoards.stop(this)com.rfsentinel.app.usb.UsbWifi.stop(this)com.rfsentinel.app.sdr.SdrRadio.stop(this)+ // Its hooks point into this service: cleared, so a stopped scan isn't kept in memory by them.+ com.rfsentinel.app.sdr.SdrRadio.onAircraft = null+ com.rfsentinel.app.sdr.SdrRadio.location = nullif (gnssWatching) { GnssWatch.stop(this, gnssListener); gnssWatching = false }- onlineWatch.stop()+ if (onlineWatchLazy.isInitialized()) onlineWatch.stop() // not built just to be stoppedcom.rfsentinel.app.esp.OuiSpyBle.stop()// External hardware is gone with the scan: its "heard by" marks (External filter, badges) go too.com.rfsentinel.app.esp.HeardBy.esp.clear()diff --git a/app/src/main/java/com/rfsentinel/app/service/TripRecorder.kt b/app/src/main/java/com/rfsentinel/app/service/TripRecorder.ktindex 71aab7d..f83bd72 100644--- a/app/src/main/java/com/rfsentinel/app/service/TripRecorder.kt+++ b/app/src/main/java/com/rfsentinel/app/service/TripRecorder.kt@@ -11,6 +11,8 @@ import java.text.SimpleDateFormatimport java.util.Dateimport java.util.Localeimport java.util.concurrent.ConcurrentHashMap+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock/*** Records a scan trace ("trip"): your GPS path, plus every device heard along@@ -25,6 +27,12 @@ object TripRecorder {private const val MIN_POINT_INTERVAL_MS = 30_000L/** Ignore fixes worse than this (indoor network fixes jump around). */private const val MAX_ACCURACY_M = 60f+ /**+ * A long wardrive hears tens of thousands of devices: past [DEVICES_IN_MEMORY], one not heard for+ * [DEVICE_IDLE_MS] (and already written) is let go from memory, and read back if it is heard again.+ */+ private const val DEVICES_IN_MEMORY = 2_000+ private const val DEVICE_IDLE_MS = 10 * 60_000Ldata class LivePoint(val time: Long, val lat: Double, val lon: Double)@@ -41,22 +49,34 @@ object TripRecorder {private val pendingPoints = mutableListOf<TripPointEntity>()private val devices = ConcurrentHashMap<String, TripDeviceEntity>()private val dirty = ConcurrentHashMap.newKeySet<String>()+ /** Devices let go from memory (all written), and which of them are flagged, for the totals. */+ private val evicted = ConcurrentHashMap.newKeySet<String>()+ private val evictedFlagged = ConcurrentHashMap.newKeySet<String>()+ @Volatile private var tripDao: com.rfsentinel.app.data.TripDao? = null+ /** One database write at a time: a flush still writing when the trip is stopped must not reopen or zero it. */+ private val writing = Mutex()@Synchronizedfun livePoints(): List<LivePoint> = points.toList()- fun deviceCount() = devices.size- fun flaggedCount() = devices.values.count { it.flagged }+ /** The latest trace point, without copying the whole trace. */+ @Synchronized+ fun lastPoint(): LivePoint? = points.lastOrNull()++ fun deviceCount() = devices.size + evicted.size+ fun flaggedCount() = devices.values.count { it.flagged } + evictedFlagged.size/** Starts a new trip. Returns its id. */suspend fun start(context: Context, name: String? = null): Long {activeTripId?.let { return it }val now = System.currentTimeMillis()val label = name ?: ("Trace " + SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(Date(now)))- val id = AppDatabase.getInstance(context).tripDao().insertTrip(TripEntity(name = label, startTime = now))+ val dao = AppDatabase.getInstance(context).tripDao()+ val id = dao.insertTrip(TripEntity(name = label, startTime = now))synchronized(this) {+ tripDao = daopoints.clear(); pendingPoints.clear()- devices.clear(); dirty.clear()+ devices.clear(); dirty.clear(); evicted.clear(); evictedFlagged.clear()distanceM = 0.0startedAt = nowactiveTripId = id@@ -85,19 +105,19 @@ object TripRecorder {val changed = takeDirty()Final(id, pendingPoints.toList(), changed, distanceM, points.size,- devices.size, devices.values.count { it.flagged }+ deviceCount(), flaggedCount()).also {// Drop the live trace too: the process often outlives the scan (and a swiped-away// app), and the live map would keep drawing the old route.points.clear(); pendingPoints.clear()- devices.clear(); dirty.clear()+ devices.clear(); dirty.clear(); evicted.clear(); evictedFlagged.clear()distanceM = 0.0activeTripId = null}}/** Writes a detached trip and closes it; deletes it if nothing was recorded. */- suspend fun persist(context: Context, f: Final) {+ suspend fun persist(context: Context, f: Final) = writing.withLock {val dao = AppDatabase.getInstance(context).tripDao()if (f.points.isNotEmpty()) dao.insertPoints(f.points)if (f.devices.isNotEmpty()) f.devices.chunked(300).forEach { dao.upsertDevices(it) }@@ -148,7 +168,8 @@ object TripRecorder {loc: Location?, now: Long, probed: List<String> = emptyList()) {val id = activeTripId ?: return- devices.compute(mac) { _, old ->+ devices.compute(mac) { _, held ->+ val old = held ?: readBack(id, mac)val stronger = old == null || rssi > old.bestRssival hitCategory = best?.category?.name ?: old?.categoryTripDeviceEntity(@@ -173,6 +194,25 @@ object TripRecorder {dirty += mac}+ /** A device let go from memory earlier, read back from the database (null when it is new). */+ private fun readBack(id: Long, mac: String): TripDeviceEntity? {+ if (!evicted.remove(mac)) return null+ evictedFlagged.remove(mac)+ return runCatching { tripDao?.deviceNow(id, mac) }.getOrNull()+ }++ /** Lets go of devices not heard for a while (see [DEVICES_IN_MEMORY]); only ones already written. */+ private fun evictIdle(now: Long) {+ if (devices.size <= DEVICES_IN_MEMORY) return+ for ((mac, d) in devices) {+ if (now - d.lastSeen < DEVICE_IDLE_MS || mac in dirty) continue+ evicted += mac+ if (d.flagged) evictedFlagged += mac+ // Changed meanwhile (heard again): it stays.+ if (!devices.remove(mac, d)) { evicted -= mac; evictedFlagged -= mac }+ }+ }+/** Network names asked for so far plus new ones, oldest first, at most 16 (null when none). */internal fun mergeProbed(old: List<String>, new: List<String>): String? {if (new.isEmpty()) return old.ifEmpty { null }?.joinToString("\n")@@ -181,21 +221,27 @@ object TripRecorder {}/** Writes buffered points / changed devices and the trip's running totals. */- suspend fun flush(context: Context, closing: Boolean = false) {- val id = activeTripId ?: return+ suspend fun flush(context: Context, closing: Boolean = false) = writing.withLock {+ val id: Longval newPoints: List<TripPointEntity>val changed: List<TripDeviceEntity>val totalPoints: Int+ val distance: Doublesynchronized(this) {+ id = activeTripId ?: return@withLocknewPoints = pendingPoints.toList(); pendingPoints.clear()changed = takeDirty()totalPoints = points.size+ distance = distanceM}val dao = AppDatabase.getInstance(context).tripDao()if (newPoints.isNotEmpty()) dao.insertPoints(newPoints)if (changed.isNotEmpty()) changed.chunked(300).forEach { dao.upsertDevices(it) }+ // Stopped while writing: the trip's final totals come from persist (which waits for this), not from here.+ if (activeTripId != id) return@withLock+ evictIdle(System.currentTimeMillis())dao.updateStats(- id, if (closing) System.currentTimeMillis() else null, distanceM,+ id, if (closing) System.currentTimeMillis() else null, distance,totalPoints, deviceCount(), flaggedCount())}@@ -209,6 +255,6 @@ object TripRecorder {val end = pts.lastOrNull()?.time ?: open.startTimevar dist = 0.0pts.zipWithNext { a, b -> dist += DeviceRegistry.metersBetween(a.lat, a.lon, b.lat, b.lon) }- dao.updateStats(open.id, end, dist, pts.size, dao.devices(open.id).size, dao.devices(open.id).count { it.flagged })+ dao.updateStats(open.id, end, dist, pts.size, dao.deviceCount(open.id), dao.flaggedCount(open.id))}}diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.ktindex b247c2a..d7d3527 100644--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt@@ -6,11 +6,11 @@ import android.os.Bundleimport android.provider.Settingsimport android.view.Viewimport android.widget.RadioButton+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.ui.CustomThemesimport com.rfsentinel.app.ui.ThemeManagerimport com.rfsentinel.app.ui.ThemeImportimport android.widget.Toast-import androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivityimport androidx.lifecycle.lifecycleScopeimport com.google.android.material.switchmaterial.SwitchMaterial@@ -119,7 +119,7 @@ class SettingsActivity : AppCompatActivity() {(runCatching { d.name }.getOrNull() ?: d.address) + if (car) " (car audio)" else ""}.toTypedArray()val checked = paired.map { it.address in chosen }.toBooleanArray()- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Which Bluetooth is your car?").setMultiChoiceItems(labels, checked) { _, i, on ->if (on) chosen += paired[i].address else chosen -= paired[i].address@@ -142,7 +142,7 @@ class SettingsActivity : AppCompatActivity() {chosen.map { a -> bonded.firstOrNull { it.address == a }?.let { runCatching { it.name }.getOrNull() } ?: a }} else chosen.toList()binding.carDevicesText.text = "Car: " + names.joinToString()- binding.carDevicesText.visibility = if (names.isEmpty()) View.GONE else View.VISIBLE+ binding.carDevicesText.shownIf(names.isNotEmpty())}/** Ignored trackers (long-press a tracker > Ignore this tracker) and a paused follow warning. */@@ -156,16 +156,16 @@ class SettingsActivity : AppCompatActivity() {java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date(until)))}binding.trackerIgnoreText.text = parts.joinToString("; ")- binding.trackerIgnoreText.visibility = if (parts.isEmpty()) View.GONE else View.VISIBLE- binding.trackerIgnoreButton.visibility = if (n > 0 || paused) android.view.View.VISIBLE else android.view.View.GONE+ binding.trackerIgnoreText.shownIf(parts.isNotEmpty())+ binding.trackerIgnoreButton.shownIf(n > 0 || paused)}/** Known cameras silenced from the map (tap a camera > Ignore alerts). */private fun updateIgnoredCamerasText() {val n = com.rfsentinel.app.alpr.IgnoredCameras.count(this)binding.ignoredCamerasText.text = "$n camera${if (n == 1) "" else "s"} with alerts turned off · faded on the map"- binding.ignoredCamerasText.visibility = if (n > 0) View.VISIBLE else View.GONE- binding.ignoredCamerasButton.visibility = if (n > 0) android.view.View.VISIBLE else android.view.View.GONE+ binding.ignoredCamerasText.shownIf(n > 0)+ binding.ignoredCamerasButton.shownIf(n > 0)}/** ESP32 boards on USB (OUI-Spy / GhostESP / Marauder) and an OUI-SPY board over Bluetooth. */@@ -221,7 +221,7 @@ class SettingsActivity : AppCompatActivity() {}val names = listOf("Automatic (best English voice)") + list.mapIndexed { i, v -> label(v, i) }val sel = Prefs.voiceName(this)?.let { n -> list.indexOfFirst { it.name == n } + 1 } ?: 0- androidx.appcompat.app.AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Voice for spoken alerts").setSingleChoiceItems(names.toTypedArray(), sel) { _, which ->// Each pick is spoken right away so you can compare.@@ -305,7 +305,7 @@ class SettingsActivity : AppCompatActivity() {else -> "Record what the USB WiFi adapter or V2X board hears, for Wireshark"}binding.pcapButton.text = if (rec.active) "Stop and share" else "Record frames"- binding.pcapShareButton.visibility = if (!rec.active && file != null) View.VISIBLE else View.GONE+ binding.pcapShareButton.shownIf(!rec.active && file != null)binding.pcapText.removeCallbacks(pcapTicker)if (rec.active) binding.pcapText.postDelayed(pcapTicker, 1_000)}@@ -334,7 +334,7 @@ class SettingsActivity : AppCompatActivity() {if (!com.rfsentinel.app.esp.OuiSpyBle.canConnect(this)) {ouiSpyConnectPermission.launch(android.Manifest.permission.BLUETOOTH_CONNECT); return}- val looking = AlertDialog.Builder(this)+ val looking = MaterialAlertDialogBuilder(this).setTitle("Looking for OUI-SPY boards…").setMessage("Keep the board powered and close by.").setNegativeButton("Cancel", null)@@ -359,7 +359,7 @@ class SettingsActivity : AppCompatActivity() {val labels = boards.map { "${it.name} (${it.mac}, ${it.rssi} dBm)" }.toMutableList()if (current != null) labels += "Forget the paired board"if (labels.isEmpty()) {- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("No OUI-SPY board found").setMessage("Check that:\n\n" +"• the board runs the Bluetooth \"App-Controlled\" firmware and has power\n" +@@ -372,7 +372,7 @@ class SettingsActivity : AppCompatActivity() {.show()return}- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Which OUI-SPY board?").setItems(labels.toTypedArray()) { _, i ->if (i < boards.size) {@@ -645,7 +645,7 @@ class SettingsActivity : AppCompatActivity() {setBackgroundResource(ripple)contentDescription = "About $title"setOnClickListener {- AlertDialog.Builder(this@SettingsActivity).setTitle(title).setMessage(s.info)+ MaterialAlertDialogBuilder(this@SettingsActivity).setTitle(title).setMessage(s.info).setPositiveButton("OK", null).show()}}@@ -706,7 +706,7 @@ class SettingsActivity : AppCompatActivity() {setPadding((10 * dp).toInt(), (8 * dp).toInt(), (6 * dp).toInt(), (8 * dp).toInt())setBackgroundResource(ripple)contentDescription = "About ${title()}"- setOnClickListener { AlertDialog.Builder(this@SettingsActivity).setTitle(title()).setMessage(text).setPositiveButton("OK", null).show() }+ setOnClickListener { MaterialAlertDialogBuilder(this@SettingsActivity).setTitle(title()).setMessage(text).setPositiveButton("OK", null).show() }}}@@ -825,6 +825,17 @@ class SettingsActivity : AppCompatActivity() {/** Views tinted as search matches, with the background they had before. */private val highlighted = mutableListOf<Pair<View, android.graphics.drawable.Drawable?>>()+ /** 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.+ */+ private fun View.shownIf(on: Boolean) {+ setTag(R.id.search_hidden, null)+ visibility = if (on) View.VISIBLE else View.GONE+ }private lateinit var searchInput: android.widget.EditText/** The search field pinned above the scrolling settings (with a clear button). */@@ -878,7 +889,7 @@ class SettingsActivity : AppCompatActivity() {val ripple = android.util.TypedValue().also { theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, it, true) }.resourceIdreturn android.widget.TextView(this).apply {text = "Collapse all"- textSize = 13f+ textSize = 14fsetTypeface(typeface, android.graphics.Typeface.BOLD)setTextColor(com.google.android.material.color.MaterialColors.getColor(this, androidx.appcompat.R.attr.colorPrimary, currentTextColor))setPadding((10 * dp).toInt(), (10 * dp).toInt(), (12 * dp).toInt(), (10 * dp).toInt())@@ -908,6 +919,8 @@ class SettingsActivity : AppCompatActivity() {private fun filterSettings(raw: String) {highlighted.forEach { (v, bg) -> v.background = bg }highlighted.clear()+ searchHidden.forEach { if (it.getTag(R.id.search_hidden) == true) { it.setTag(R.id.search_hidden, null); it.visibility = View.VISIBLE } }+ searchHidden.clear()val q = raw.trim().lowercase()if (q.isEmpty()) {sectionUi.forEach { it.row.visibility = View.VISIBLE; it.divider?.visibility = View.VISIBLE; it.restore() }@@ -924,6 +937,8 @@ class SettingsActivity : AppCompatActivity() {s.divider?.visibility = s.row.visibilityif (!show) { s.body.visibility = View.GONE; continue }s.expand()+ // Only the matching settings, unless the section's own name matches.+ if (hits.isNotEmpty() && !s.title.lowercase().contains(q)) (s.body as? android.view.ViewGroup)?.let { narrow(it, hits) }for (v in hits) {highlighted += v to v.backgroundv.background = android.graphics.drawable.ColorDrawable(tint)@@ -942,6 +957,50 @@ class SettingsActivity : AppCompatActivity() {}}+ /**+ * Hides the settings in [box] with no match in [hits]. A setting is its label (or switch, check box,+ * button) with what follows it up to the next one: the choices, number field or options under it.+ * A match in the label shows the whole setting; a match further down shows the label and that part,+ * looking inside an options panel for just the matching options. Returns whether anything is left.+ */+ private fun narrow(box: android.view.ViewGroup, hits: List<View>): Boolean {+ fun holdsHit(v: View) = hits.any { h -> generateSequence(h) { it.parent as? View }.any { it === v } }+ fun startsSetting(v: View): Boolean = when (v) {+ is android.widget.RadioGroup -> false+ is android.widget.EditText -> false+ is android.widget.TextView -> true // a label, switch, check box or button+ is android.widget.LinearLayout -> v.orientation == android.widget.LinearLayout.HORIZONTAL &&+ v.childCount > 0 && startsSetting(v.getChildAt(0)) // a label or switch with its ⓘ+ else -> false+ }+ fun hide(v: View) {+ if (v.visibility == View.GONE) return+ v.visibility = View.GONE+ v.setTag(R.id.search_hidden, true)+ searchHidden += v+ }+ val groups = mutableListOf<MutableList<View>>()+ for (i in 0 until box.childCount) {+ val c = box.getChildAt(i)+ if (c.visibility == View.GONE) continue+ if (groups.isEmpty() || startsSetting(c)) groups += mutableListOf(c) else groups.last() += c+ }+ var any = false+ for (g in groups) {+ val head = g.first().takeIf { startsSetting(it) }+ if (head != null && holdsHit(head)) { any = true; continue }+ var shown = false+ for (v in g) {+ if (v === head) continue+ val keep = holdsHit(v) && (v !is android.widget.LinearLayout || v is android.widget.RadioGroup ||+ v.orientation == android.widget.LinearLayout.HORIZONTAL || narrow(v, hits))+ if (keep) shown = true else hide(v)+ }+ if (shown) any = true else head?.let { hide(it) }+ }+ return any+ }+/** Visible settings under [v] whose label, text or hint contains [q]. */private fun collectMatches(v: View, q: String, out: MutableList<View>) {if (v is android.view.ViewGroup) {@@ -978,7 +1037,7 @@ class SettingsActivity : AppCompatActivity() {if (text == null) { Toast.makeText(this, "Couldn't read that file (or it is too big for a backup)", Toast.LENGTH_LONG).show(); return@registerForActivityResult }val found = when (val i = backup.inspect(text)) {is com.rfsentinel.app.util.SettingsBackup.Inspect.Bad -> {- androidx.appcompat.app.AlertDialog.Builder(this).setTitle("Not restored").setMessage(i.why).setPositiveButton("OK", null).show()+ MaterialAlertDialogBuilder(this).setTitle("Not restored").setMessage(i.why).setPositiveButton("OK", null).show()return@registerForActivityResult}is com.rfsentinel.app.util.SettingsBackup.Inspect.Ok -> i@@ -988,7 +1047,7 @@ class SettingsActivity : AppCompatActivity() {val labels = found.sections.map { s ->if (s == com.rfsentinel.app.util.SettingsBackup.Section.THEMES) "${s.label}: ${found.themes}" else s.label}.toTypedArray()- androidx.appcompat.app.AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Restore what? Ticked parts are replaced, then RF Sentinel restarts").setMultiChoiceItems(labels, BooleanArray(labels.size) { true }) { _, which, on ->if (on) chosen += found.sections[which] else chosen -= found.sections[which]@@ -996,7 +1055,7 @@ class SettingsActivity : AppCompatActivity() {.setPositiveButton("Restore") { _, _ ->if (chosen.isEmpty()) { Toast.makeText(this, "Nothing ticked - nothing restored", Toast.LENGTH_SHORT).show(); return@setPositiveButton }when (val r = backup.restore(this, text, chosen)) {- is com.rfsentinel.app.util.SettingsBackup.Result.Refused -> androidx.appcompat.app.AlertDialog.Builder(this)+ is com.rfsentinel.app.util.SettingsBackup.Result.Refused -> MaterialAlertDialogBuilder(this).setTitle("Not restored").setMessage(r.why).setPositiveButton("OK", null).show()is com.rfsentinel.app.util.SettingsBackup.Result.Restored -> {restored = true@@ -1236,7 +1295,7 @@ class SettingsActivity : AppCompatActivity() {switch("Plate readers", Prefs.navAvoidPlateReaders(this)) { Prefs.setNavAvoidPlateReaders(this, it) }label("Places")- val places = android.widget.TextView(this).apply { textSize = 13f; alpha = 0.8f }+ 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" +"Work: ${Prefs.navWork(this@SettingsActivity)?.name ?: "not set"}\n" +@@ -1247,7 +1306,7 @@ class SettingsActivity : AppCompatActivity() {box.addView(com.google.android.material.button.MaterialButton(this, null, com.google.android.material.R.attr.materialButtonOutlinedStyle).apply {text = "Forget saved and recent places"setOnClickListener {- AlertDialog.Builder(this@SettingsActivity)+ MaterialAlertDialogBuilder(this@SettingsActivity).setTitle("Forget your places?").setMessage("Removes Home, Work, starred and recent destinations from this phone.").setPositiveButton("Forget") { _, _ ->@@ -1357,7 +1416,7 @@ class SettingsActivity : AppCompatActivity() {startActivity(Intent(this, com.rfsentinel.app.ui.TripsActivity::class.java))}binding.mapDeleteCamerasButton.setOnClickListener {- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Delete downloaded cameras?").setMessage("Removes the saved plate, speed, red-light and CCTV cameras. They download again as you use the map.").setPositiveButton("Delete") { _, _ ->@@ -1429,7 +1488,7 @@ class SettingsActivity : AppCompatActivity() {return@setOnClickListener}val current = all.indexOf(com.rfsentinel.app.ui.MapEngine.chosen(this))- androidx.appcompat.app.AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Map provider").setSingleChoiceItems(all.map { it.label }.toTypedArray(), current) { d, which ->Prefs.setMapProvider(this, all[which].key)@@ -1447,13 +1506,13 @@ class SettingsActivity : AppCompatActivity() {textSize = 12falpha = 0.75fsetPadding((24 * resources.displayMetrics.density).toInt(), 0, 0, (6 * resources.displayMetrics.density).toInt())- visibility = if (text.isBlank()) View.GONE else View.VISIBLE+ shownIf(text.isNotBlank())}private fun showNote(view: android.widget.TextView?, text: String) {view ?: returnview.text = text- view.visibility = if (text.isBlank()) View.GONE else View.VISIBLE+ view.shownIf(text.isNotBlank())}/**@@ -1476,7 +1535,7 @@ class SettingsActivity : AppCompatActivity() {/** Pick the radar-detector sound effect; each choice plays as a preview. */private fun chooseDetectorEffect() {var picked = Prefs.detectorEffect(this)- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Detector sound effect").setSingleChoiceItems(detectorEffectNames, picked) { _, which ->picked = which@@ -1495,7 +1554,7 @@ class SettingsActivity : AppCompatActivity() {val texts = mutableListOf<android.widget.TextView>()fun slider(label: (Int) -> String, from: Int, to: Int, value: Int, save: (Int) -> Unit): com.google.android.material.slider.Slider {val text = android.widget.TextView(this).apply {- textSize = 13f+ textSize = 14fsetPadding(0, (10 * resources.displayMetrics.density).toInt(), 0, 0)this.text = label(value)}@@ -1572,9 +1631,9 @@ class SettingsActivity : AppCompatActivity() {aircraftStatusText = android.widget.TextView(this).apply { textSize = 12f; alpha = 0.75f }box.addView(aircraftStatusText)showNote(aircraftStatusText, com.rfsentinel.app.online.OnlineWatch.aircraftStatus)- box.visibility = if (sw.isChecked) View.VISIBLE else View.GONE+ box.shownIf(sw.isChecked)binding.categoryContainer.addView(box)- sw.setOnCheckedChangeListener { _, on -> box.visibility = if (on) View.VISIBLE else View.GONE }+ sw.setOnCheckedChangeListener { _, on -> box.shownIf(on) }}/**@@ -1635,7 +1694,7 @@ class SettingsActivity : AppCompatActivity() {val steps = if (direct) Prefs.WAZE_DIRECT_INTERVALS_S else Prefs.WAZE_NINJA_INTERVALS_Sval col = android.widget.LinearLayout(this).apply { orientation = android.widget.LinearLayout.VERTICAL }val text = android.widget.TextView(this).apply { textSize = 12f; alpha = 0.75f }- val hint = android.widget.TextView(this).apply { textSize = 11f; alpha = 0.6f }+ val hint = android.widget.TextView(this).apply { textSize = 12f; alpha = 0.6f }fun show(sec: Int) {text.text = "Check for new reports every ${Prefs.formatInterval(sec)}"hint.text = when {@@ -1644,7 +1703,7 @@ class SettingsActivity : AppCompatActivity() {sec > 90 -> "Over 90 s Waze ends the session in between, so each check logs in again (more data)."else -> ""}- hint.visibility = if (hint.text.isEmpty()) View.GONE else View.VISIBLE+ hint.shownIf(hint.text.isNotEmpty())}val now = Prefs.wazeIntervalS(this, direct)show(now)@@ -1748,10 +1807,10 @@ class SettingsActivity : AppCompatActivity() {}box.addView(wazeKeyInput)fun showBackend(direct: Boolean) {- wazeKeyInput?.visibility = if (direct) View.GONE else View.VISIBLE- directInterval.visibility = if (direct) View.VISIBLE else View.GONE- ninjaInterval.visibility = if (direct) View.GONE else View.VISIBLE- directBox.visibility = if (direct) View.VISIBLE else View.GONE+ wazeKeyInput?.shownIf(!direct)+ directInterval.shownIf(direct)+ ninjaInterval.shownIf(!direct)+ directBox.shownIf(direct)}val directNow = Prefs.wazeBackend(this) == Prefs.WAZE_DIRECTbackendGroup.check(if (directNow) directBtn.id else ninjaBtn.id)@@ -1761,7 +1820,7 @@ class SettingsActivity : AppCompatActivity() {if (Prefs.wazeDirectAccepted(this)) { Prefs.setWazeBackend(this, Prefs.WAZE_DIRECT); showBackend(true) }else {backendGroup.check(ninjaBtn.id)- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Waze direct: use at your own risk").setMessage(WAZE_DIRECT_WARNING).setPositiveButton("I understand, use direct") { _, _ ->@@ -1781,13 +1840,13 @@ class SettingsActivity : AppCompatActivity() {text = "Waze status"setOnClickListener { com.rfsentinel.app.ui.WazeUi.openStatus(this@SettingsActivity) }})- box.visibility = if (sw.isChecked) View.VISIBLE else View.GONE+ box.shownIf(sw.isChecked)binding.categoryContainer.addView(box)sw.setOnCheckedChangeListener { _, on ->if (on && !Prefs.wazeReady(this)) {sw.isChecked = falseval direct = Prefs.wazeBackend(this) == Prefs.WAZE_DIRECT- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Waze reports: use at your own risk").setMessage(if (direct) WAZE_DIRECT_WARNING else WAZE_WARNING).setPositiveButton("I understand, enable") { _, _ ->@@ -1799,7 +1858,7 @@ class SettingsActivity : AppCompatActivity() {.show()return@setOnCheckedChangeListener}- box.visibility = if (on) View.VISIBLE else View.GONE+ box.shownIf(on)}}@@ -1866,13 +1925,13 @@ class SettingsActivity : AppCompatActivity() {if (t == ThemeManager.AppTheme.MATERIAL_YOU && !ThemeManager.isDynamicColorAvailable) " (this phone: standard Material 3 colours)" else ""} + "\n\nYour own themes are listed after these: long-press one to edit it."box.addView(infoRow(android.widget.TextView(this).apply {- text = "Theme"; setPadding(0, (10 * resources.displayMetrics.density).toInt(), 0, 0); textSize = 13f+ text = "Theme"; setPadding(0, (10 * resources.displayMetrics.density).toInt(), 0, 0); textSize = 14f}, themesInfo), at - 1)btn("Create a custom theme...") { editTheme(null) }btn("Edit a theme...") {val all = CustomThemes.all(this)if (all.isEmpty()) Toast.makeText(this, "You have no custom themes yet", Toast.LENGTH_SHORT).show()- else AlertDialog.Builder(this).setTitle("Edit which theme?")+ else MaterialAlertDialogBuilder(this).setTitle("Edit which theme?").setItems(all.map { it.name }.toTypedArray()) { _, i -> editTheme(all[i].id) }.show()}btn("Import a theme file...") { themeFilePicker.launch(arrayOf("application/json", "text/plain", "*/*")) }@@ -1886,7 +1945,7 @@ class SettingsActivity : AppCompatActivity() {val box = binding.sectionAppearanceval dp = resources.displayMetrics.densitybox.addView(infoRow(android.widget.TextView(this).apply {- text = "Screen style"; setPadding(0, (14 * dp).toInt(), 0, 0); textSize = 13f+ text = "Screen style"; setPadding(0, (14 * dp).toInt(), 0, 0); textSize = 14f}, "On: the screen shows gauges, signal bars and charts.\n\nOff: the plain text list it had before.\n\n" +"Each of these screens also has a list / visual button at the top to switch it there."))com.rfsentinel.app.ui.VisualMode.Screen.values().forEach { s ->@@ -2076,7 +2135,7 @@ class SettingsActivity : AppCompatActivity() {binding.floatingMapSwitch.setOnCheckedChangeListener { sw, on ->if (on && !Settings.canDrawOverlays(this)) {sw.isChecked = false- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Allow the floating map").setMessage("Android needs the \"Display over other apps\" permission for the floating map. " +"Turn it on for RF Sentinel on the next screen, then come back and switch the map on.")@@ -2093,7 +2152,7 @@ class SettingsActivity : AppCompatActivity() {binding.bubbleSwitch.setOnCheckedChangeListener { sw, on ->if (on && !Settings.canDrawOverlays(this)) {sw.isChecked = false- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Allow the floating bubble").setMessage("Android needs the \"Display over other apps\" permission for the bubble. " +"Turn it on for RF Sentinel on the next screen, then come back and switch the bubble on.")@@ -2269,7 +2328,7 @@ class SettingsActivity : AppCompatActivity() {"Android throttles WiFi scans: under 30 s is wasted unless you turn it off"else"Scan throttling is off: down to 5 s works"- binding.wifiThrottleButton.visibility = if (throttled) View.VISIBLE else View.GONE+ binding.wifiThrottleButton.shownIf(throttled)}/**@@ -2292,7 +2351,7 @@ class SettingsActivity : AppCompatActivity() {return}// Explain first, then open About phone: a dialog shown behind it would go unseen.- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Unlock Developer options first").setMessage("1. In About phone, tap \"Build number\" 7 times (enter your PIN if asked).\n" +@@ -2315,7 +2374,7 @@ class SettingsActivity : AppCompatActivity() {else runCatching { Settings.Global.getInt(contentResolver, "wifi_scan_throttle_enabled", 1) != 0 }.getOrDefault(true)private fun confirm(title: String, message: String, action: () -> Unit) {- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle(title).setMessage(message).setPositiveButton("Clear") { _, _ -> action() }diff --git a/app/src/main/java/com/rfsentinel/app/ui/AboutDialog.kt b/app/src/main/java/com/rfsentinel/app/ui/AboutDialog.ktindex d30f44b..d442496 100644--- a/app/src/main/java/com/rfsentinel/app/ui/AboutDialog.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/AboutDialog.kt@@ -2,9 +2,9 @@ package com.rfsentinel.app.uiimport android.text.method.LinkMovementMethodimport android.widget.TextView-import androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivityimport androidx.core.text.HtmlCompat+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.BuildConfig/** Version, scope, and where every signature and lookup table comes from. */@@ -64,9 +64,9 @@ object AboutDialog {movementMethod = LinkMovementMethod.getInstance()val pad = (20 * resources.displayMetrics.density).toInt()setPadding(pad, pad / 2, pad, 0)- textSize = 13f+ textSize = 14f}- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle("About & sources").setView(android.widget.ScrollView(activity).apply { addView(view) }).setPositiveButton("Close", null)diff --git a/app/src/main/java/com/rfsentinel/app/ui/AlertCards.kt b/app/src/main/java/com/rfsentinel/app/ui/AlertCards.ktindex 6d9ecb5..3269e5d 100644--- a/app/src/main/java/com/rfsentinel/app/ui/AlertCards.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/AlertCards.kt@@ -75,7 +75,7 @@ internal class AlertCardController(}fun show(c: AlertCards.Card) {- if (System.currentTimeMillis() < Prefs.alertsSnoozedUntil(ctx)) return+ // Shown while snoozed too: snooze silences sound and voice, not what's on screen.current = cval discreet = Prefs.discreetMode(ctx)val color = c.category.colorArgbdiff --git a/app/src/main/java/com/rfsentinel/app/ui/CellTowersActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/CellTowersActivity.ktindex bbebe54..40b4bc7 100644--- a/app/src/main/java/com/rfsentinel/app/ui/CellTowersActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/CellTowersActivity.kt@@ -7,13 +7,13 @@ import android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.TextView-import androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivityimport androidx.lifecycle.Lifecycleimport androidx.lifecycle.lifecycleScopeimport androidx.lifecycle.repeatOnLifecycleimport androidx.recyclerview.widget.LinearLayoutManagerimport androidx.recyclerview.widget.RecyclerView+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.databinding.ActivityLogBindingimport com.rfsentinel.app.databinding.ItemDetectionBindingimport com.rfsentinel.app.detect.CellAnalyzer@@ -67,7 +67,7 @@ class CellTowersActivity : AppCompatActivity() {val v = when (viewType) {0 -> TextView(parent.context).apply {setTypeface(typeface, Typeface.BOLD)- textSize = 15f+ textSize = 16fsetPadding(0, (16 * resources.displayMetrics.density).toInt(), 0, (6 * resources.displayMetrics.density).toInt())}3 -> ServingCard()@@ -140,12 +140,12 @@ class CellTowersActivity : AppCompatActivity() {private val dp = resources.displayMetrics.densityprivate val accent = ChipStyle.accent(context).firstprivate val ratChip = TextView(context).apply { textSize = 12f; setTypeface(typeface, Typeface.BOLD) }- private val title = TextView(context).apply { textSize = 17f; setTypeface(typeface, Typeface.BOLD) }+ private val title = TextView(context).apply { textSize = 16f; setTypeface(typeface, Typeface.BOLD) }private val dbm = TextView(context).apply { textSize = 34f; setTypeface(typeface, Typeface.BOLD) }- private val unit = TextView(context).apply { textSize = 13f; alpha = 0.75f; text = " dBm" }+ private val unit = TextView(context).apply { textSize = 14f; alpha = 0.75f; text = " dBm" }private val bars = SignalBarsView(context)private val spark = SparklineView(context)- private val sparkLabel = TextView(context).apply { textSize = 11f; alpha = 0.7f }+ private val sparkLabel = TextView(context).apply { textSize = 12f; alpha = 0.7f }private val idText = TextView(context).apply { textSize = 12f; typeface = Typeface.MONOSPACE; alpha = 0.85f }init {@@ -292,7 +292,7 @@ class CellTowersActivity : AppCompatActivity() {append("\nThe map position is where your phone was when this tower's signal was strongest - ")append("an estimate, usually within a few hundred metres to a few km of the real tower.")}- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle(t.ratLabel).setMessage(text).apply {diff --git a/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.ktindex 7f4d07b..92ee541 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.kt@@ -4,10 +4,10 @@ import android.os.Bundleimport android.view.Menuimport android.view.MenuItemimport android.view.View-import androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivityimport androidx.lifecycle.lifecycleScopeimport androidx.recyclerview.widget.LinearLayoutManager+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.data.AppDatabaseimport com.rfsentinel.app.databinding.ActivityLogBindingimport com.rfsentinel.app.util.Exporter@@ -49,7 +49,7 @@ class DetectionLogActivity : AppCompatActivity() {override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {1 -> { Exporter.showExportMenu(this); true }2 -> {- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Clear match history?").setMessage("This deletes every logged match on this device. Export first if you need a copy.").setPositiveButton("Clear") { _, _ ->diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.ktindex bfa2d71..7a4986f 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt@@ -10,9 +10,9 @@ import android.widget.LinearLayoutimport android.widget.ScrollViewimport android.widget.TextViewimport android.widget.Toast-import androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivityimport androidx.lifecycle.lifecycleScope+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.BuildConfigimport com.rfsentinel.app.data.AppDatabaseimport com.rfsentinel.app.data.Favorites@@ -67,10 +67,12 @@ object DeviceActions {if (custom != null) {items += "Remove from watchlist (${custom.prefix})" to {OuiWatchlist.removeCustomEntry(activity, custom.prefix)- toast(activity, "Removed from watchlist")+ com.rfsentinel.app.util.Undo.show(activity, "Removed from watchlist") {+ OuiWatchlist.addCustomEntry(activity, custom)+ }}} else {- items += "Add to watchlist..." to { addToWatchlist(activity, mac, snap?.name) }+ items += "Add to watchlist..." to { addToWatchlist(activity, mac, snap?.name, snap?.advert?.isWifi == true) }}when {ignoredTracker -> items += "Stop ignoring this tracker" to {@@ -93,7 +95,7 @@ object DeviceActions {}items += "Copy address" to { copy(activity, mac) }- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle(snap?.best?.label ?: snap?.name ?: mac).setItems(items.map { it.first }.toTypedArray()) { _, which -> items[which].second() }.show()@@ -101,9 +103,10 @@ object DeviceActions {/*** Adds a device to the watchlist, either as this exact device (full MAC, the- * default) or as its whole vendor prefix (disabled for randomized addresses).+ * default), as its whole vendor prefix (disabled for randomized addresses), or+ * as every network / device whose name starts the same way (an SSID prefix).*/- fun addToWatchlist(activity: AppCompatActivity, mac: String, name: String?) {+ fun addToWatchlist(activity: AppCompatActivity, mac: String, name: String?, wifi: Boolean = false) {val oui = MacUtil.oui(mac)val randomized = MacUtil.isRandomized(mac)val b = DialogAddWatchlistBinding.inflate(activity.layoutInflater)@@ -131,20 +134,40 @@ object DeviceActions {if (randomized) b.warningText.text = "This is a randomized (private) address: it may change later. " +"The probe fingerprint below stays the same - watch that to catch this type of device."}+ // The start of its name / SSID: catches the whole family ("Flock-..."), whatever the address.+ val named = name?.trim().orEmpty()+ if (named.isNotEmpty()) {+ b.scopeStarts.visibility = View.VISIBLE+ b.scopeStarts.text = if (wifi) "Every network whose name (SSID) starts with:" else "Every device whose name starts with:"+ b.startsInput.setText(named)+ b.scopeGroup.setOnCheckedChangeListener { _, id ->+ b.startsInput.visibility = if (id == b.scopeStarts.id) View.VISIBLE else View.GONE+ if (id == b.scopeStarts.id) b.startsInput.requestFocus()+ }+ if (randomized && fp == null) b.warningText.text = "This is a randomized (private) address: it may change later, and its " ++ "prefix is not a real vendor, so prefix matching is disabled. Tip: watch the start of its name instead."+ }b.labelInput.setText(name ?: "")- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle("Add to watchlist").setView(b.root).setPositiveButton("Add") { _, _ ->val wholePrefix = b.scopePrefix.isCheckedval byFingerprint = fp != null && b.scopeFingerprint.isCheckedval byShape = shape != null && b.scopeShape.isChecked+ val start = b.startsInput.text.toString().trim()+ val byStart = named.isNotEmpty() && b.scopeStarts.isChecked+ if (byStart && start.isEmpty()) { toast(activity, "Not added: enter the start of the name"); return@setPositiveButton }val key = when {+ byStart -> OuiEntry.STARTS + startbyShape -> OuiEntry.FINGERPRINT + shape; byFingerprint -> OuiEntry.FINGERPRINT + fpwholePrefix -> oui; else -> mac}- val label = b.labelInput.text.toString().trim().ifEmpty {+ // The label box holds the device's own full name: for a name prefix, say what is watched instead.+ val typed = b.labelInput.text.toString().trim().takeUnless { byStart && it == named }.orEmpty()+ val label = typed.ifEmpty {when {+ byStart -> (if (wifi) "SSID starts with " else "Name starts with ") + startbyShape -> "Probe shape ${shape!!.removePrefix("shape-")}"; byFingerprint -> "Device type $fp"wholePrefix -> "Custom prefix $oui"; else -> "Custom device $mac"}@@ -167,7 +190,7 @@ object DeviceActions {val note = EditText(activity).apply { hint = "What do you think it is? (optional)"; setSingleLine(false) }val preview = TextView(activity).apply {typeface = Typeface.MONOSPACE- textSize = 11f+ textSize = 12fsetTextIsSelectable(true)}fun report() = SignatureReport.build(advert, snap.vendor, snap.deviceType, MacUtil.isRandomized(mac),@@ -184,7 +207,7 @@ object DeviceActions {addView(note)addView(preview)}- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle("Report unknown device").setView(ScrollView(activity).apply { addView(box) }).setPositiveButton("Share") { _, _ ->@@ -218,11 +241,11 @@ object DeviceActions {val title = android.widget.TextView(activity).apply {val d = resources.displayMetrics.densitysetPadding((24 * d).toInt(), (20 * d).toInt(), (24 * d).toInt(), (8 * d).toInt())- textSize = 15f+ textSize = 16ftext = "Ignore this tracker?\n\nIts Bluetooth address changes about once a day, so it can't be " +"whitelisted like other devices. Only ignore a tag you know - a hidden tracker would stay silent too."}- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setCustomTitle(title).setItems(choices) { _, which ->when (which) {@@ -245,7 +268,7 @@ object DeviceActions {}fun whitelist(activity: AppCompatActivity, mac: String, label: String) {- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle("Whitelist this device?").setMessage("$mac\n$label\n\nIt will be marked trusted and never logged, flashed or alerted on.").setPositiveButton("Whitelist") { _, _ ->@@ -260,8 +283,12 @@ object DeviceActions {fun unwhitelist(activity: AppCompatActivity, mac: String) {activity.lifecycleScope.launch {- AppDatabase.getInstance(activity).whitelistDao().remove(WhitelistEntity(mac))- toast(activity, "Removed $mac from the whitelist")+ val dao = AppDatabase.getInstance(activity).whitelistDao()+ val was = dao.get(mac) ?: WhitelistEntity(mac)+ dao.remove(was)+ com.rfsentinel.app.util.Undo.show(activity, "Removed $mac from the whitelist") {+ activity.lifecycleScope.launch { dao.add(was) }+ }}}diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.ktindex 9b9f8f8..09a5d4f 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt@@ -16,6 +16,7 @@ import androidx.lifecycle.Lifecycleimport androidx.lifecycle.lifecycleScopeimport androidx.lifecycle.repeatOnLifecycleimport com.google.android.material.button.MaterialButton+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.util.AlertPlayerimport com.rfsentinel.app.data.AppDatabaseimport com.rfsentinel.app.data.DetectionEntity@@ -74,6 +75,13 @@ class DeviceDetailActivity : AppCompatActivity() {supportActionBar?.setDisplayHomeAsUpEnabled(true)binding.locateButton.setOnClickListener { toggleLocate() }+ // The main action in the theme's highlight colour (faded while the device isn't heard).+ ChipStyle.accent(this).let { (accent, onAccent) ->+ val off = intArrayOf(-android.R.attr.state_enabled)+ val on = intArrayOf()+ binding.locateButton.backgroundTintList = android.content.res.ColorStateList(arrayOf(off, on), intArrayOf((accent and 0x00FFFFFF) or 0x55000000, accent))+ binding.locateButton.setTextColor(android.content.res.ColorStateList(arrayOf(off, on), intArrayOf((onAccent and 0x00FFFFFF) or 0x99000000.toInt(), onAccent)))+ }binding.actionWatchlist.setOnClickListener { onWatchlistAction() }binding.actionWhitelist.setOnClickListener {val s = DeviceRegistry.get(mac)@@ -390,7 +398,7 @@ class DeviceDetailActivity : AppCompatActivity() {container.addView(TextView(this).apply {text = titlesetTypeface(typeface, Typeface.BOLD)- setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f)+ setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)setPadding(0, (18 * dp).toInt(), 0, (4 * dp).toInt())})if (visual && title == "Why it's flagged" && hits.isNotEmpty()) {@@ -403,7 +411,7 @@ class DeviceDetailActivity : AppCompatActivity() {setPadding(0, (3 * dp).toInt(), 0, (3 * dp).toInt())addView(TextView(context).apply {text = k- setTextSize(TypedValue.COMPLEX_UNIT_SP, 11f)+ setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f)setTextColor(0xFF888888.toInt())})addView(TextView(context).apply {@@ -434,10 +442,10 @@ class DeviceDetailActivity : AppCompatActivity() {addView(LinearLayout(context).apply {orientation = LinearLayout.HORIZONTAL; gravity = android.view.Gravity.CENTER_VERTICALaddView(TextView(context).apply {- text = h.label; setTypeface(typeface, Typeface.BOLD); setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f)+ text = h.label; setTypeface(typeface, Typeface.BOLD); setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)}, LinearLayout.LayoutParams(0, -2, 1f))addView(TextView(context).apply {- text = "${h.confidence}%"; setTypeface(typeface, Typeface.BOLD); setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f); setTextColor(color)+ text = "${h.confidence}%"; setTypeface(typeface, Typeface.BOLD); setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f); setTextColor(color)})})addView(LevelBarView(context).apply { set(h.confidence / 100f, color) },@@ -448,11 +456,11 @@ class DeviceDetailActivity : AppCompatActivity() {evidenceKinds(h.evidence).forEach { addView(VisualMode.chip(context, it, ChipStyle.accent(context).first)) }})addView(TextView(context).apply {- text = h.evidence; setTextIsSelectable(true); setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f)+ text = h.evidence; setTextIsSelectable(true); setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)setPadding(0, (8 * dp).toInt(), 0, 0)})addView(TextView(context).apply {- text = "Source: ${h.source}"; setTextIsSelectable(true); setTextSize(TypedValue.COMPLEX_UNIT_SP, 11f); alpha = 0.7f+ text = "Source: ${h.source}"; setTextIsSelectable(true); setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f); alpha = 0.7fsetPadding(0, (4 * dp).toInt(), 0, 0)})}@@ -534,7 +542,7 @@ class DeviceDetailActivity : AppCompatActivity() {val box = android.widget.FrameLayout(this).apply {val side = (20 * dp).toInt(); setPadding(side, (8 * dp).toInt(), side, 0); addView(input)}- androidx.appcompat.app.AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle(title).setView(box).setPositiveButton("Save") { _, _ -> done(input.text.toString()) }@@ -553,16 +561,19 @@ class DeviceDetailActivity : AppCompatActivity() {val custom = OuiWatchlist.customEntry(mac) ?: OuiWatchlist.customEntry(MacUtil.oui(mac))if (custom != null) {OuiWatchlist.removeCustomEntry(this, custom.prefix)- Toast.makeText(this, "Removed ${custom.prefix} from the watchlist", Toast.LENGTH_SHORT).show()+ com.rfsentinel.app.util.Undo.show(this, "Removed ${custom.prefix} from the watchlist") {+ OuiWatchlist.addCustomEntry(this, custom)+ }} else {- DeviceActions.addToWatchlist(this, mac, DeviceRegistry.get(mac)?.name ?: known?.name)+ DeviceActions.addToWatchlist(this, mac, DeviceRegistry.get(mac)?.name ?: known?.name,+ DeviceRegistry.get(mac)?.advert?.isWifi == true)}}private fun share() {val s = DeviceRegistry.get(mac)if (s?.advert != null && s.best == null) {- androidx.appcompat.app.AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Share").setItems(arrayOf("Full device report", "Report unknown device (signature only)")) { _, which ->if (which == 0) shareFull(s) else DeviceActions.reportUnknown(this, mac)diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.ktindex df9ef5b..734be89 100644--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.kt@@ -16,6 +16,7 @@ import androidx.recyclerview.widget.LinearLayoutManagerimport androidx.recyclerview.widget.ListAdapterimport androidx.recyclerview.widget.RecyclerViewimport com.google.android.material.chip.Chip+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.data.AppDatabaseimport com.rfsentinel.app.data.KnownDeviceDaoimport com.rfsentinel.app.data.KnownDeviceEntity@@ -128,7 +129,7 @@ class DeviceHistoryActivity : AppCompatActivity() {private fun importFrom(uri: android.net.Uri) {val progress = android.widget.TextView(this).apply { text = "Reading the file..."; setPadding(64, 32, 64, 8) }- val dialog = androidx.appcompat.app.AlertDialog.Builder(this).setTitle("Importing device history").setView(progress).setCancelable(false).show()+ val dialog = MaterialAlertDialogBuilder(this).setTitle("Importing device history").setView(progress).setCancelable(false).show()lifecycleScope.launch {val result = runCatching {kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {@@ -145,14 +146,14 @@ class DeviceHistoryActivity : AppCompatActivity() {val r = result.getOrNull()if (r == null) {val why = (result.exceptionOrNull() as? com.rfsentinel.app.util.DeviceHistoryImport.NotHistory)?.message ?: "Couldn't read that file (${result.exceptionOrNull()?.message ?: "unknown error"})"- androidx.appcompat.app.AlertDialog.Builder(this@DeviceHistoryActivity).setTitle("Not imported").setMessage(why).setPositiveButton("OK", null).show()+ MaterialAlertDialogBuilder(this@DeviceHistoryActivity).setTitle("Not imported").setMessage(why).setPositiveButton("OK", null).show()return@launch}com.rfsentinel.app.data.Favorites.load(this@DeviceHistoryActivity)com.rfsentinel.app.data.DeviceNames.load(this@DeviceHistoryActivity)search(now = true)val keep = Prefs.retentionDays(this@DeviceHistoryActivity)- androidx.appcompat.app.AlertDialog.Builder(this@DeviceHistoryActivity).setTitle("History imported")+ MaterialAlertDialogBuilder(this@DeviceHistoryActivity).setTitle("History imported").setMessage("${r.added} new devices, ${r.updated} updated, ${r.unchanged} already there" +(if (r.skipped > 0) ", ${r.skipped} entries skipped (not a device)" else "") + "." +(if (keep > 0) "\n\nDevices not seen for more than $keep days are removed again at the next scan unless starred (Settings > Data > Keep history)." else ""))diff --git a/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.ktindex dd166e5..8b408f0 100644--- a/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/GnssActivity.kt@@ -48,7 +48,7 @@ class GnssActivity : AppCompatActivity() {override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {val v = if (viewType == 0) TextView(parent.context).apply {setTypeface(typeface, Typeface.BOLD)- textSize = 15f+ textSize = 16fsetPadding(0, (16 * resources.displayMetrics.density).toInt(), 0, (6 * resources.displayMetrics.density).toInt())} else ItemDetectionBinding.inflate(LayoutInflater.from(parent.context), parent, false).rootreturn object : RecyclerView.ViewHolder(v) {}@@ -119,7 +119,7 @@ class GnssActivity : AppCompatActivity() {val accent = ChipStyle.accent(this@GnssActivity).firstval box = android.widget.LinearLayout(this@GnssActivity).apply { orientation = android.widget.LinearLayout.VERTICAL }val root = android.widget.ScrollView(this@GnssActivity).apply { addView(box); visibility = View.GONE }- val verdict = TextView(this@GnssActivity).apply { textSize = 15f; setTypeface(typeface, Typeface.BOLD) }+ val verdict = TextView(this@GnssActivity).apply { textSize = 16f; setTypeface(typeface, Typeface.BOLD) }val verdictSub = TextView(this@GnssActivity).apply { textSize = 12f; alpha = 0.8f }val tiles = android.widget.FrameLayout(this@GnssActivity)val sky = SkyPlotView(this@GnssActivity)@@ -144,7 +144,7 @@ class GnssActivity : AppCompatActivity() {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,- TextView(this@GnssActivity).apply { text = "Filled: used for your position. Outlined: heard only."; textSize = 11f; alpha = 0.7f }))+ TextView(this@GnssActivity).apply { text = "Filled: used for your position. Outlined: heard only."; textSize = 12f; alpha = 0.7f }))}fun show(snap: GnssAnalyzer.Snapshot, verdictText: String, sub: String, good: Boolean) {diff --git a/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.ktindex eb5f4e5..9cb9b8b 100644--- a/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/HistoryActivity.kt@@ -2,9 +2,9 @@ package com.rfsentinel.app.uiimport android.os.Bundleimport android.view.MenuItem-import androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivityimport androidx.lifecycle.lifecycleScope+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.Rimport com.rfsentinel.app.data.AppDatabaseimport com.rfsentinel.app.databinding.ActivityHistoryBinding@@ -177,7 +177,7 @@ class HistoryActivity : AppCompatActivity() {m.query(android.graphics.RectF(x - r, y - r, x + r, y + r), listOf(POINTS to "i")) { found ->if (isFinishing || isDestroyed) return@queryval e = found.firstOrNull()?.firstOrNull()?.toIntOrNull()?.let { shown.getOrNull(it) } ?: return@query- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle(e.label).setMessage("${dateFmt.format(Date(e.time))}\n${e.mac}").setPositiveButton("Details") { _, _ -> DeviceActions.openDetails(this, e.mac) }diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.ktindex fd721df..00ed84f 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt@@ -15,7 +15,6 @@ import android.view.Viewimport android.view.ViewGroupimport android.widget.EditTextimport android.widget.Toast-import androidx.appcompat.app.AlertDialogimport androidx.core.view.MenuProviderimport androidx.core.view.ViewCompatimport androidx.core.view.WindowInsetsCompat@@ -25,6 +24,7 @@ import androidx.fragment.app.Fragmentimport androidx.lifecycle.Lifecycleimport androidx.lifecycle.lifecycleScopeimport androidx.lifecycle.repeatOnLifecycle+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.data.AppDatabaseimport com.rfsentinel.app.data.TripDeviceEntityimport com.rfsentinel.app.data.TripEntity@@ -41,6 +41,7 @@ import com.rfsentinel.app.service.TripRecorderimport com.rfsentinel.app.util.Exporterimport com.rfsentinel.app.util.Permissionsimport com.rfsentinel.app.util.Prefs+import kotlinx.coroutines.asyncimport kotlinx.coroutines.delayimport kotlinx.coroutines.isActiveimport kotlinx.coroutines.launch@@ -1145,7 +1146,7 @@ class MapFragment : Fragment() {/** A saved trace: glides to where you are (the map doesn't follow you there). */private fun centerOnMe() {- val p = myPosition() ?: TripRecorder.livePoints().lastOrNull()?.let { it.lat to it.lon }+ val p = myPosition() ?: TripRecorder.lastPoint()?.let { it.lat to it.lon }if (p != null) map?.easeTo(p.first, p.second, ms = 600)else Toast.makeText(act, "Waiting for a GPS fix...", Toast.LENGTH_SHORT).show()}@@ -1354,13 +1355,17 @@ class MapFragment : Fragment() {private fun toggleRecording() {if (TripRecorder.isRecording) {+ val id = TripRecorder.activeTripId+ // Written in the app's scope: leaving the map (or rotating) mid-write must not lose the trace.+ val app = act.application as com.rfsentinel.app.RFSentinelApp+ val ended = TripRecorder.detach()+ val saving = app.appScope.async { ended?.let { runCatching { TripRecorder.persist(app, it) } } }viewLifecycleOwner.lifecycleScope.launch {- val id = TripRecorder.activeTripId- TripRecorder.stop(act)+ saving.await()refreshServiceLocation()val saved = id?.let { AppDatabase.getInstance(act).tripDao().get(it) }if (saved != null) {- AlertDialog.Builder(act)+ MaterialAlertDialogBuilder(act).setTitle("Trace saved").setMessage(String.format(Locale.US, "%s\n%s · %s (%d flagged)",saved.name, com.rfsentinel.app.util.Units.trip(saved.distanceM), devicesLabel(saved.deviceCount), saved.flaggedCount))@@ -1542,7 +1547,7 @@ class MapFragment : Fragment() {private fun rename(id: Long) {val input = EditText(act).apply { setText(trip?.name ?: ""); setSelection(text.length) }- AlertDialog.Builder(act)+ MaterialAlertDialogBuilder(act).setTitle("Rename trace").setView(input).setPositiveButton("Save") { _, _ ->@@ -1556,7 +1561,7 @@ class MapFragment : Fragment() {}private fun confirmDelete(id: Long) {- AlertDialog.Builder(act)+ MaterialAlertDialogBuilder(act).setTitle("Delete this trace?").setMessage("The route and its device list are deleted from this phone.").setPositiveButton("Delete") { _, _ ->diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapSafetyUi.kt b/app/src/main/java/com/rfsentinel/app/ui/MapSafetyUi.ktindex 19176a2..12921a1 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapSafetyUi.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapSafetyUi.kt@@ -1,8 +1,8 @@package com.rfsentinel.app.uiimport android.widget.Toast-import androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivity+import com.google.android.material.dialog.MaterialAlertDialogBuilder/** What the screens tell the user after [MapSafety.recover] found that the app closed while the map was starting. */internal object MapSafetyUi {@@ -25,7 +25,7 @@ internal object MapSafetyUi {onTryAgain?.invoke()}MapSafety.Recovery.MAP_OFF -> {- val b = AlertDialog.Builder(activity).setTitle(OFF_TITLE).setCancelable(onTryAgain == null)+ val b = MaterialAlertDialogBuilder(activity).setTitle(OFF_TITLE).setCancelable(onTryAgain == null)if (onTryAgain == null) b.setMessage(OFF_MESSAGE).setPositiveButton("OK", null)else b.setMessage("$OFF_MESSAGE\n\nTry the map again now?").setPositiveButton("Try the map again") { _, _ -> onTryAgain() }diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapShared.kt b/app/src/main/java/com/rfsentinel/app/ui/MapShared.ktindex 1c5f585..ee829e6 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MapShared.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MapShared.kt@@ -2,8 +2,8 @@ package com.rfsentinel.app.uiimport android.content.Intentimport android.widget.Toast-import androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivity+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.service.DeviceRegistryimport java.util.Locale@@ -65,7 +65,7 @@ internal object MapDialogs {if (list.isEmpty()) returnif (list.size == 1) { showPin(a, list[0]); return }val sorted = list.sortedByDescending { it.flagged }- AlertDialog.Builder(a)+ MaterialAlertDialogBuilder(a).setTitle("${list.size} devices here").setItems(sorted.map { (if (it.flagged) "⚠ " else "") + it.label }.toTypedArray()) { _, i -> showPin(a, sorted[i]) }.setNegativeButton("Close", null)@@ -73,7 +73,7 @@ internal object MapDialogs {}fun showPin(a: AppCompatActivity, p: MapPin) {- AlertDialog.Builder(a)+ MaterialAlertDialogBuilder(a).setTitle(p.label).setMessage(p.details + "\n\n" + p.whereNote).setPositiveButton("Details") { _, _ -> DeviceActions.openDetails(a, p.mac) }@@ -82,7 +82,7 @@ internal object MapDialogs {}fun showWaze(a: AppCompatActivity, w: com.rfsentinel.app.online.WazePolice.Shown) {- AlertDialog.Builder(a)+ MaterialAlertDialogBuilder(a).setTitle(w.hit.label).setMessage("${w.hit.tier.label} ${w.hit.confidence}%\n${com.rfsentinel.app.online.WazePolice.relativeText(w.where, w.trend)}\n${w.hit.evidence}").setNegativeButton("Close", null)@@ -105,7 +105,7 @@ internal object MapDialogs {DeviceRegistry.metersBetween(it.first, it.second, p.lat, p.lon)) + "\n") }append("ICAO address: ${p.hex.uppercase()}\nSource: community ADS-B (adsb.fi / adsb.lol)")}- AlertDialog.Builder(a)+ MaterialAlertDialogBuilder(a).setTitle(hit?.label ?: (p.registration ?: p.callsign ?: "Aircraft")).setMessage(text).setPositiveButton("OK", null)@@ -126,7 +126,7 @@ internal object MapDialogs {}fun showDrone(a: AppCompatActivity, mac: String, text: String) {- AlertDialog.Builder(a)+ MaterialAlertDialogBuilder(a).setTitle("Drone (Remote ID)").setMessage(text + "\n\nPositions are broadcast by the drone itself (ASTM F3411 Remote ID).").setPositiveButton("Details") { _, _ -> DeviceActions.openDetails(a, mac) }@@ -152,7 +152,7 @@ internal object MapDialogs {"signal, so the scan can't detect them - this layer shows the ones that have been mapped. " +"The shaded area is an estimate of what it sees.\n\nMap data © OpenStreetMap contributors (ODbL).")}- AlertDialog.Builder(a)+ MaterialAlertDialogBuilder(a).setTitle(com.rfsentinel.app.alpr.Cctv.title(c)).setMessage(text).setPositiveButton("Close", null)@@ -180,7 +180,7 @@ internal object MapDialogs {append("OSM: ${cam.osmId}\n\n")append("These cameras send their data over cellular or wire and have no Bluetooth/WiFi signature, so they can't be detected by radio - this map is the only warning. Mobile speed cameras move and are rarely mapped.\n\nMap data © OpenStreetMap contributors (ODbL).")}- AlertDialog.Builder(a)+ MaterialAlertDialogBuilder(a).setTitle(cam.label).setMessage(text)// Kept until turned back on here (or cleared in Settings).@@ -209,7 +209,7 @@ internal object MapDialogs {private fun pickDirection(a: AppCompatActivity, cam: com.rfsentinel.app.alpr.KnownCamera, current: Int?, onChanged: () -> Unit) {val items = COMPASS.map { "Faces ${it.lowercase()}" } + "Not set"val checked = current?.let { ((it + 22) % 360) / 45 } ?: COMPASS.size- AlertDialog.Builder(a)+ MaterialAlertDialogBuilder(a).setTitle("Which way does it face?").setSingleChoiceItems(items.toTypedArray(), checked) { d, i ->com.rfsentinel.app.alpr.CameraDirections.set(a, cam.osmId, if (i < COMPASS.size) i * 45 else null)@@ -223,7 +223,7 @@ internal object MapDialogs {fun showTower(a: AppCompatActivity, t: com.rfsentinel.app.service.CellTowerStore.Tower) {val net = listOfNotNull(t.operator, "${t.mcc ?: "?"}-${t.mnc ?: "?"}").joinToString(" · ")val dateFmt = java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.MEDIUM, java.text.DateFormat.SHORT)- AlertDialog.Builder(a)+ MaterialAlertDialogBuilder(a).setTitle(t.ratLabel).setMessage("$net\nArea ${t.area ?: "?"} · Cell ${t.cellId}" +(t.bestDbm?.let { "\nStrongest signal $it dBm" } ?: "") +diff --git a/app/src/main/java/com/rfsentinel/app/ui/MarkerPicker.kt b/app/src/main/java/com/rfsentinel/app/ui/MarkerPicker.ktindex 0876675..a2c3677 100644--- a/app/src/main/java/com/rfsentinel/app/ui/MarkerPicker.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/MarkerPicker.kt@@ -10,8 +10,8 @@ import android.widget.ImageViewimport android.widget.LinearLayoutimport android.widget.ScrollViewimport android.widget.TextView-import androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivity+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.google.android.material.slider.Sliderimport com.rfsentinel.app.util.Prefs@@ -139,7 +139,7 @@ object MarkerPicker {addView(slider)}refresh()- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle("Position marker").setView(ScrollView(activity).apply { addView(root) }).setPositiveButton("Done", null)diff --git a/app/src/main/java/com/rfsentinel/app/ui/RegionNotice.kt b/app/src/main/java/com/rfsentinel/app/ui/RegionNotice.ktindex d6d4898..2943486 100644--- a/app/src/main/java/com/rfsentinel/app/ui/RegionNotice.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/RegionNotice.kt@@ -1,7 +1,7 @@package com.rfsentinel.app.uiimport android.content.Context-import androidx.appcompat.app.AlertDialog+import com.google.android.material.dialog.MaterialAlertDialogBuilder/*** Shown when a regional preset with driving rules worth knowing is switched on: France and@@ -32,7 +32,7 @@ object RegionNotice {fun show(context: Context, preset: String) {val (title, text) = textFor(preset) ?: return- AlertDialog.Builder(context)+ MaterialAlertDialogBuilder(context).setTitle(title).setMessage(text).setPositiveButton("I understand", null)diff --git a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.ktindex 777dd7f..6eed3b9 100644--- a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt@@ -428,12 +428,12 @@ class SetupActivity : AppCompatActivity() {setPadding((16 * dp).toInt(), (12 * dp).toInt(), (16 * dp).toInt(), (12 * dp).toInt())addView(TextView(context).apply {text = (if (selected) "◉ " else "○ ") + title- setTextSize(TypedValue.COMPLEX_UNIT_SP, 17f)+ setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)setTypeface(typeface, Typeface.BOLD)})addView(TextView(context).apply {text = desc- setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f)+ setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)alpha = 0.8f})}diff --git a/app/src/main/java/com/rfsentinel/app/ui/ThemeImport.kt b/app/src/main/java/com/rfsentinel/app/ui/ThemeImport.ktindex 236ff96..68bbd1a 100644--- a/app/src/main/java/com/rfsentinel/app/ui/ThemeImport.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/ThemeImport.kt@@ -15,6 +15,7 @@ import android.widget.TextViewimport android.widget.Toastimport androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivity+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.google.android.material.materialswitch.MaterialSwitch/**@@ -37,7 +38,7 @@ object ThemeImport {}.getOrNull()if (text == null) { Toast.makeText(activity, "Couldn't read that file (or it is too big to be a theme)", Toast.LENGTH_LONG).show(); return }val shared = try { CustomThemes.parseShared(text) } catch (e: CustomThemes.BadThemeFile) {- AlertDialog.Builder(activity).setTitle("Not imported").setMessage(e.message).setPositiveButton("OK", null).show(); return+ MaterialAlertDialogBuilder(activity).setTitle("Not imported").setMessage(e.message).setPositiveButton("OK", null).show(); return}show(activity, shared, done)}@@ -102,7 +103,7 @@ object ThemeImport {where.setOnCheckedChangeListener { _, _ -> update() }update()- val dialog = AlertDialog.Builder(activity).setTitle("Import theme")+ val dialog = MaterialAlertDialogBuilder(activity).setTitle("Import theme").setView(ScrollView(activity).apply { addView(box) }).setPositiveButton("Import", null).setNegativeButton("Cancel", null).create()diff --git a/app/src/main/java/com/rfsentinel/app/ui/ThemeMakerActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/ThemeMakerActivity.ktindex b3ea638..71f7340 100644--- a/app/src/main/java/com/rfsentinel/app/ui/ThemeMakerActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/ThemeMakerActivity.kt@@ -21,12 +21,12 @@ import android.widget.TextViewimport android.widget.Toastimport androidx.activity.OnBackPressedCallbackimport androidx.activity.result.contract.ActivityResultContracts-import androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivityimport androidx.core.widget.doAfterTextChangedimport com.google.android.material.button.MaterialButtonimport com.google.android.material.card.MaterialCardViewimport com.google.android.material.color.MaterialColors+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.google.android.material.materialswitch.MaterialSwitchimport com.rfsentinel.app.util.applySystemBarInsetsimport java.io.File@@ -159,7 +159,7 @@ class ThemeMakerActivity : AppCompatActivity() {private fun leave() {if (!dirty()) { finish(); return }- AlertDialog.Builder(this).setTitle("Keep your changes?")+ MaterialAlertDialogBuilder(this).setTitle("Keep your changes?").setPositiveButton("Save") { _, _ -> if (save() != null) finish() }.setNegativeButton("Discard") { _, _ -> finish() }.setNeutralButton("Keep editing", null).show()@@ -480,7 +480,7 @@ class ThemeMakerActivity : AppCompatActivity() {addView(hex)}refresh()- AlertDialog.Builder(this).setTitle("Custom colour").setView(box)+ MaterialAlertDialogBuilder(this).setTitle("Custom colour").setView(box).setPositiveButton("Use") { _, _ -> t = t.copy(accent = current() or 0xFF000000.toInt()); updateSwatches(); updatePreview() }.setNegativeButton("Cancel", null).show()}@@ -534,7 +534,7 @@ class ThemeMakerActivity : AppCompatActivity() {}private fun confirmDelete() {- AlertDialog.Builder(this).setTitle("Delete \"${t.name}\"?")+ MaterialAlertDialogBuilder(this).setTitle("Delete \"${t.name}\"?").setMessage("Its banner and font go too. Export it first if you want to keep a copy.").setPositiveButton("Delete") { _, _ ->val wasUsed = ThemeManager.custom(this)?.id == t.iddiff --git a/app/src/main/java/com/rfsentinel/app/ui/TripsActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/TripsActivity.ktindex be12749..b631e6f 100644--- a/app/src/main/java/com/rfsentinel/app/ui/TripsActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/TripsActivity.kt@@ -6,13 +6,13 @@ import android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.EditText-import androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivityimport androidx.lifecycle.lifecycleScopeimport androidx.recyclerview.widget.DiffUtilimport androidx.recyclerview.widget.LinearLayoutManagerimport androidx.recyclerview.widget.ListAdapterimport androidx.recyclerview.widget.RecyclerView+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.data.AppDatabaseimport com.rfsentinel.app.data.TripEntityimport com.rfsentinel.app.databinding.ActivityLogBinding@@ -152,7 +152,7 @@ class TripsActivity : AppCompatActivity() {}private fun actions(t: TripEntity) {- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle(t.name).setItems(arrayOf("View on map", "Export (GPX, KML, GeoJSON, CSV)...", "Rename", "Delete")) { _, which ->when (which) {@@ -167,7 +167,7 @@ class TripsActivity : AppCompatActivity() {private fun rename(t: TripEntity) {val input = EditText(this).apply { setText(t.name); setSelection(text.length) }- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Rename trace").setView(input).setPositiveButton("Save") { _, _ ->@@ -181,11 +181,11 @@ class TripsActivity : AppCompatActivity() {private fun delete(t: TripEntity) {if (t.id == TripRecorder.activeTripId) {- AlertDialog.Builder(this).setMessage("Stop recording on the map before deleting this trace.")+ MaterialAlertDialogBuilder(this).setMessage("Stop recording on the map before deleting this trace.").setPositiveButton("OK", null).show()return}- AlertDialog.Builder(this)+ MaterialAlertDialogBuilder(this).setTitle("Delete \"${t.name}\"?").setMessage("The route and its device list are deleted from this phone.").setPositiveButton("Delete") { _, _ ->diff --git a/app/src/main/java/com/rfsentinel/app/usb/FirmwarePrompt.kt b/app/src/main/java/com/rfsentinel/app/usb/FirmwarePrompt.ktindex 870df95..b1add82 100644--- a/app/src/main/java/com/rfsentinel/app/usb/FirmwarePrompt.kt+++ b/app/src/main/java/com/rfsentinel/app/usb/FirmwarePrompt.kt@@ -6,10 +6,10 @@ import android.app.PendingIntentimport android.content.Contextimport android.content.Intentimport android.widget.Toast-import androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivityimport androidx.core.app.NotificationCompatimport androidx.lifecycle.lifecycleScope+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.Rimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.launch@@ -53,7 +53,7 @@ object FirmwarePrompt {val blobs = Firmware.missing(activity, chip.driver).ifEmpty { UsbWifi.retry(activity); return false }val kb = blobs.sumOf { it.size } / 1024val files = blobs.joinToString("\n") { "• ${it.name}" }- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle("Download the ${chip.name} firmware?").setMessage("This adapter needs its maker's firmware to run. That firmware isn't free software, so this " +"build of RF Sentinel doesn't include it.\n\nRF Sentinel can download it once (about $kb KB) from the " +diff --git a/app/src/main/java/com/rfsentinel/app/util/CrashLog.kt b/app/src/main/java/com/rfsentinel/app/util/CrashLog.ktindex 8e5f4dd..ef45165 100644--- a/app/src/main/java/com/rfsentinel/app/util/CrashLog.kt+++ b/app/src/main/java/com/rfsentinel/app/util/CrashLog.kt@@ -4,8 +4,8 @@ import android.content.Contextimport android.content.Intentimport android.os.Buildimport android.widget.Toast-import androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivity+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.BuildConfigimport java.io.Fileimport java.io.PrintWriter@@ -59,7 +59,7 @@ object CrashLog {if (!prefs.getBoolean("unseen", false)) returnprefs.edit().putBoolean("unseen", false).apply()if (!hasCrashes(activity)) return- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle("RF Sentinel closed unexpectedly").setMessage("A crash log was saved on this phone (nothing is sent automatically). " +"Sending it to the developer helps fix it.\n\nLater: Settings > Lists, tools & about > Export crash log.")diff --git a/app/src/main/java/com/rfsentinel/app/util/DeviceExport.kt b/app/src/main/java/com/rfsentinel/app/util/DeviceExport.ktindex 004cae5..3559ed8 100644--- a/app/src/main/java/com/rfsentinel/app/util/DeviceExport.kt+++ b/app/src/main/java/com/rfsentinel/app/util/DeviceExport.kt@@ -182,17 +182,43 @@ object DeviceExport {// ---- Long-term history ----------------------------------------------------------+ private const val HISTORY_CSV_HEADER = "mac,name,vendor,device_type,first_seen,last_seen,sessions,detect_count,favorite,note,custom_name\n"+fun historyCsv(rows: List<KnownDeviceEntity>): String {- val sb = StringBuilder("mac,name,vendor,device_type,first_seen,last_seen,sessions,detect_count,favorite,note,custom_name\n")- rows.forEach { r ->- sb.append(r.mac).append(',').append(q(r.name)).append(',').append(q(r.vendor)).append(',')- .append(q(r.deviceType)).append(',').append(local(r.firstSeen)).append(',').append(local(r.lastSeen)).append(',')- .append(r.sessions).append(',').append(r.detectCount).append(',').append(r.favorite).append(',')- .append(q(r.note)).append(',').append(q(r.alias)).append('\n')- }+ val sb = StringBuilder(HISTORY_CSV_HEADER)+ rows.forEach { r -> historyCsvLine(sb, r) }return sb.toString()}+ private fun historyCsvLine(sb: StringBuilder, r: KnownDeviceEntity) {+ sb.append(r.mac).append(',').append(q(r.name)).append(',').append(q(r.vendor)).append(',')+ .append(q(r.deviceType)).append(',').append(local(r.firstSeen)).append(',').append(local(r.lastSeen)).append(',')+ .append(r.sessions).append(',').append(r.detectCount).append(',').append(r.favorite).append(',')+ .append(q(r.note)).append(',').append(q(r.alias)).append('\n')+ }++ /**+ * The device history as CSV or JSON, written straight to [out] a batch at a time ([batches] gives the next+ * rows, empty when done): 100,000+ devices built up as one string ran the app out of memory.+ */+ suspend fun writeHistory(out: java.io.Writer, csv: Boolean, batches: suspend () -> List<KnownDeviceEntity>) {+ if (csv) {+ out.write(HISTORY_CSV_HEADER)+ val sb = StringBuilder()+ while (true) {+ val rows = batches(); if (rows.isEmpty()) break+ sb.setLength(0); rows.forEach { historyCsvLine(sb, it) }; out.write(sb.toString())+ }+ } else {+ val w = gson.newJsonWriter(out)+ w.beginArray()+ while (true) { val rows = batches(); if (rows.isEmpty()) break; rows.forEach { gson.toJson(historyItem(it), w) } }+ w.endArray()+ w.flush()+ }+ out.flush()+ }+fun historyJson(rows: List<KnownDeviceEntity>): JsonArray = JsonArray().apply { rows.forEach { add(historyItem(it)) } }private fun historyItem(r: KnownDeviceEntity) = JsonObject().apply {diff --git a/app/src/main/java/com/rfsentinel/app/util/Exporter.kt b/app/src/main/java/com/rfsentinel/app/util/Exporter.ktindex 26bb95a..49593bf 100644--- a/app/src/main/java/com/rfsentinel/app/util/Exporter.kt+++ b/app/src/main/java/com/rfsentinel/app/util/Exporter.kt@@ -4,10 +4,10 @@ import android.content.Contextimport android.content.Intentimport android.net.Uriimport android.widget.Toast-import androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivityimport androidx.core.content.FileProviderimport androidx.lifecycle.lifecycleScope+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.data.AppDatabaseimport com.rfsentinel.app.data.DetectionEntityimport com.rfsentinel.app.oui.OuiWatchlist@@ -46,7 +46,7 @@ object Exporter {/** Two steps: what to export, then which format. */fun showExportMenu(activity: AppCompatActivity) {val scopes = Scope.entries- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle("Export").setItems(scopes.map { it.title }.toTypedArray()) { _, which -> chooseFormat(activity, scopes[which]) }.setNegativeButton("Cancel", null)@@ -64,7 +64,7 @@ object Exporter {run(activity, scope, scope.formats[0])return}- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle(scope.title).setItems(scope.formats.map { FORMAT_LABELS.getValue(it) }.toTypedArray()) { _, which ->run(activity, scope, scope.formats[which])@@ -120,18 +120,10 @@ object Exporter {val detections = db.detectionDao()val session = sessionDevices()shareWritten(activity, "rf_sentinel_full_export_${stamp()}.json", "application/json", "Export") { out ->- // The order is fixed first, so devices heard meanwhile don't shift the batches.- val macs = history.macsByLastSeen()- var at = 0var before = Long.MAX_VALUEDeviceExport.writeEverything(out, com.rfsentinel.app.BuildConfig.VERSION_NAME, session, flags,- historyBatches = {- val chunk = macs.subList(at.coerceAtMost(macs.size), (at + BATCH).coerceAtMost(macs.size))- at += BATCH- val order = chunk.withIndex().associate { (i, m) -> m to i }- if (chunk.isEmpty()) emptyList() else history.getAll(chunk).sortedBy { order[it.mac] ?: Int.MAX_VALUE }- },+ historyBatches = historyBatches(history, history.macsByLastSeen()),matchBatches = { detections.pageBefore(before, BATCH).also { rows -> rows.lastOrNull()?.let { before = it.id } } },watchlist = OuiWatchlist.allEntries().filter { it.isCustom })@@ -140,9 +132,36 @@ object Exporter {private const val BATCH = 500+ /**+ * The device history a batch at a time, newest first. [macs] fixes the order first, so devices heard+ * meanwhile don't shift the batches.+ */+ private fun historyBatches(+ history: com.rfsentinel.app.data.KnownDeviceDao, macs: List<String>+ ): suspend () -> List<com.rfsentinel.app.data.KnownDeviceEntity> {+ var at = 0+ return {+ val chunk = macs.subList(at.coerceAtMost(macs.size), (at + BATCH).coerceAtMost(macs.size))+ at += BATCH+ val order = chunk.withIndex().associate { (i, m) -> m to i }+ if (chunk.isEmpty()) emptyList() else history.getAll(chunk).sortedBy { order[it.mac] ?: Int.MAX_VALUE }+ }+ }+private fun exportDevices(activity: AppCompatActivity, scope: Scope, format: String) {launchExport(activity) {val db = AppDatabase.getInstance(activity)+ if (scope == Scope.HISTORY) {+ // Written a batch at a time: a long history doesn't fit in memory as one string.+ val history = db.knownDeviceDao()+ val macs = history.macsByLastSeen()+ if (macs.isEmpty()) { toast(activity, "No device history yet"); return@launchExport }+ val csv = format == "csv"+ shareWritten(activity, "rf_sentinel_device_history_${stamp()}.$format", if (csv) "text/csv" else "application/json", "Export") { out ->+ DeviceExport.writeHistory(out, csv, historyBatches(history, macs))+ }+ return@launchExport+ }val session = sessionDevices()val (name, text, mime) = withContext(Dispatchers.Default) {when (scope) {@@ -185,14 +204,14 @@ object Exporter {"GeoJSON - web maps, QGIS","CSV - devices heard on this trace (spreadsheet)")- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle("Export trace").setItems(labels) { _, which ->val format = formats[which]if (format == "csv") {exportTrip(activity, tripId, format, onlyFlagged = false)} else {- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle("Which devices?").setItems(arrayOf("All devices heard on the trace", "Flagged devices only")) { _, w ->exportTrip(activity, tripId, format, onlyFlagged = w == 1)diff --git a/app/src/main/java/com/rfsentinel/app/util/Undo.kt b/app/src/main/java/com/rfsentinel/app/util/Undo.ktnew file mode 100644index 0000000..db0a47d--- /dev/null+++ b/app/src/main/java/com/rfsentinel/app/util/Undo.kt@@ -0,0 +1,13 @@+package com.rfsentinel.app.util++import android.app.Activity+import android.view.View+import com.google.android.material.snackbar.Snackbar++/** A short note after removing something, with Undo to put it back (a toast can't take it back). */+object Undo {+ fun show(activity: Activity, message: String, undo: () -> Unit) {+ val root = activity.findViewById<View>(android.R.id.content) ?: return+ Snackbar.make(root, message, Snackbar.LENGTH_LONG).setAction("Undo") { undo() }.show()+ }+}diff --git a/app/src/main/java/com/rfsentinel/app/util/UpdateChecker.kt b/app/src/main/java/com/rfsentinel/app/util/UpdateChecker.ktindex 19bc49e..87fef6c 100644--- a/app/src/main/java/com/rfsentinel/app/util/UpdateChecker.kt+++ b/app/src/main/java/com/rfsentinel/app/util/UpdateChecker.kt@@ -3,9 +3,9 @@ package com.rfsentinel.app.utilimport android.content.Intentimport android.net.Uriimport android.widget.Toast-import androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivityimport androidx.lifecycle.lifecycleScope+import com.google.android.material.dialog.MaterialAlertDialogBuilderimport com.rfsentinel.app.BuildConfigimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.launch@@ -117,7 +117,7 @@ object UpdateChecker {if (activity.isFinishing || activity.isDestroyed) return@launchif (silent && result.isFailure) return@launchval latest = result.getOrElse {- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle("Couldn't check for updates").setMessage("GitHub couldn't be reached (${it.message ?: "no connection"}). You can look at the releases page instead.").setPositiveButton("Open releases") { _, _ -> open(activity, RELEASES) }@@ -128,7 +128,7 @@ object UpdateChecker {val current = BuildConfig.VERSION_NAME.substringBefore('-')if (isNewer(latest.version, current) && BuildConfig.FLAVOR == "foss" && !signedByUs(activity)) {// Built and signed by F-Droid: Android would refuse our APK over it, so F-Droid updates it.- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle("RF Sentinel ${latest.version} is available").setMessage("You have $current. This copy was built and signed by F-Droid, so it updates through F-Droid " +"once F-Droid has built the new version.")@@ -136,7 +136,7 @@ object UpdateChecker {.setNeutralButton("What's new") { _, _ -> open(activity, latest.notesUrl) }.show()} else if (isNewer(latest.version, current)) {- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle("RF Sentinel ${latest.version} is available").setMessage("You have $current. It downloads here and installs over this one - your history and settings are kept. " +"Scanning stops while it installs.")@@ -145,7 +145,7 @@ object UpdateChecker {.setNegativeButton("Later", null).show()} else if (!silent) {- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle("You're up to date").setMessage("RF Sentinel $current is the latest version.").setPositiveButton("OK", null)@@ -172,7 +172,7 @@ object UpdateChecker {addView(text); addView(bar, android.widget.LinearLayout.LayoutParams(-1, -2).apply { topMargin = (12 * d).toInt() })}var job: kotlinx.coroutines.Job? = null- val dialog = AlertDialog.Builder(activity)+ val dialog = MaterialAlertDialogBuilder(activity).setTitle("Updating to RF Sentinel ${latest.version}").setView(box).setCancelable(false)@@ -210,7 +210,7 @@ object UpdateChecker {}private fun failed(activity: AppCompatActivity, latest: Latest, why: String) {- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle("Couldn't install the update").setMessage("$why\n\nYou can download RF Sentinel ${latest.version} from GitHub and install it yourself.").setPositiveButton("Open release page") { _, _ -> open(activity, latest.notesUrl) }@@ -220,7 +220,7 @@ object UpdateChecker {/** Android asks each app to be allowed to install apps: one switch, then the update carries on from here. */private fun askToAllowInstalls(activity: AppCompatActivity, latest: Latest) {- AlertDialog.Builder(activity)+ MaterialAlertDialogBuilder(activity).setTitle("Allow RF Sentinel to install updates").setMessage("Android needs you to allow this once: it opens a switch called \"Allow from this source\". " +"Turn it on, come back, and the update starts by itself. Nothing else is installed this way.")diff --git a/app/src/main/java/com/rfsentinel/app/whitelist/WhitelistActivity.kt b/app/src/main/java/com/rfsentinel/app/whitelist/WhitelistActivity.ktindex 6274da3..92ff577 100644--- a/app/src/main/java/com/rfsentinel/app/whitelist/WhitelistActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/whitelist/WhitelistActivity.kt@@ -25,7 +25,11 @@ class WhitelistActivity : AppCompatActivity() {adapter = WhitelistAdapter(entries) { entry ->lifecycleScope.launch {- AppDatabase.getInstance(this@WhitelistActivity).whitelistDao().remove(entry)+ val dao = AppDatabase.getInstance(this@WhitelistActivity).whitelistDao()+ dao.remove(entry)+ com.rfsentinel.app.util.Undo.show(this@WhitelistActivity, "Removed ${entry.mac}") {+ lifecycleScope.launch { dao.add(entry) }+ }}}binding.recyclerView.layoutManager = LinearLayoutManager(this)diff --git a/app/src/main/res/layout/activity_antenna_check.xml b/app/src/main/res/layout/activity_antenna_check.xmlindex cd20e18..f2f7556 100644--- a/app/src/main/res/layout/activity_antenna_check.xml+++ b/app/src/main/res/layout/activity_antenna_check.xml@@ -41,7 +41,7 @@android:layout_width="match_parent"android:layout_height="wrap_content"android:paddingBottom="8dp"- android:textSize="14sp" />+ android:textSize="@dimen/text_body" /><androidx.recyclerview.widget.RecyclerViewandroid:id="@+id/apList"@@ -82,7 +82,7 @@android:drawablePadding="6dp"android:ellipsize="end"android:maxLines="1"- android:textSize="15sp"+ android:textSize="@dimen/text_subtitle"android:textStyle="bold" /><TextView@@ -94,7 +94,7 @@android:paddingTop="3dp"android:paddingEnd="10dp"android:paddingBottom="3dp"- android:textSize="12sp"+ android:textSize="@dimen/text_caption"android:textStyle="bold" /></LinearLayout>@@ -102,7 +102,7 @@android:id="@+id/refTitle"android:layout_width="match_parent"android:layout_height="wrap_content"- android:textSize="17sp"+ android:textSize="@dimen/text_subtitle"android:textStyle="bold" /><TextView@@ -111,7 +111,7 @@android:layout_height="wrap_content"android:layout_marginTop="2dp"android:minLines="2"- android:textSize="13sp" />+ android:textSize="@dimen/text_body" /><com.google.android.material.button.MaterialButtonandroid:id="@+id/changeButton"@@ -135,7 +135,7 @@android:layout_width="match_parent"android:layout_height="wrap_content"android:letterSpacing="0.08"- android:textSize="13sp"+ android:textSize="@dimen/text_body"android:textStyle="bold" /><com.rfsentinel.app.ui.AntennaMeterView@@ -151,7 +151,7 @@android:layout_marginTop="10dp"android:minLines="2"android:padding="12dp"- android:textSize="15sp" />+ android:textSize="@dimen/text_subtitle" /><LinearLayoutandroid:id="@+id/chainButtons"@@ -184,7 +184,7 @@android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="6dp"- android:textSize="14sp"+ android:textSize="@dimen/text_body"android:textStyle="bold" /></LinearLayout>@@ -193,7 +193,7 @@android:layout_height="wrap_content"android:layout_marginTop="16dp"android:text="Swap test"- android:textSize="15sp"+ android:textSize="@dimen/text_subtitle"android:textStyle="bold" /><LinearLayout@@ -226,30 +226,30 @@android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="6dp"- android:textSize="14sp" />+ android:textSize="@dimen/text_body" /><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="16dp"- android:textColor="#888888"- android:textSize="12sp"+ android:textColor="?android:attr/textColorSecondary"+ android:textSize="@dimen/text_caption"android:text="Zero: with two identical antennas on, makes them read 0 dB apart. Identify: cover one antenna for 5 s to find which port it is on." /><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="8dp"- android:textColor="#888888"- android:textSize="12sp"+ android:textColor="?android:attr/textColorSecondary"+ android:textSize="@dimen/text_caption"android:text="Swap test: capture with antenna A, swap to antenna B, capture again. Each capture averages the last 5 s; keep the phone still." /><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="8dp"- android:textColor="#888888"- android:textSize="12sp"+ android:textColor="?android:attr/textColorSecondary"+ android:textSize="@dimen/text_caption"android:text="This compares how strongly each antenna hears the reference access point. It doesn't measure SWR or impedance. While this screen is open the adapter stays on the reference's channel." /></LinearLayout></ScrollView>@@ -261,6 +261,6 @@android:layout_gravity="center"android:gravity="center"android:padding="24dp"- android:textColor="#888888"+ android:textColor="?android:attr/textColorSecondary"android:visibility="gone" /></FrameLayout>diff --git a/app/src/main/res/layout/activity_device_detail.xml b/app/src/main/res/layout/activity_device_detail.xmlindex d8c487e..c08f77b 100644--- a/app/src/main/res/layout/activity_device_detail.xml+++ b/app/src/main/res/layout/activity_device_detail.xml@@ -20,7 +20,7 @@android:paddingEnd="8dp"android:paddingBottom="2dp"android:textColor="#FFFFFF"- android:textSize="12sp"+ android:textSize="@dimen/text_caption"android:textStyle="bold"android:visibility="gone" />@@ -29,7 +29,7 @@android:layout_width="match_parent"android:layout_height="wrap_content"android:textIsSelectable="true"- android:textSize="20sp"+ android:textSize="@dimen/text_title"android:textStyle="bold" /><TextView@@ -38,15 +38,15 @@android:layout_height="wrap_content"android:fontFamily="monospace"android:textIsSelectable="true"- android:textSize="13sp" />+ android:textSize="@dimen/text_body" /><TextViewandroid:id="@+id/presenceText"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="4dp"- android:textColor="#888888"- android:textSize="12sp" />+ android:textColor="?android:attr/textColorSecondary"+ android:textSize="@dimen/text_caption" /><!-- Your own note on the device: tap to edit --><TextView@@ -57,7 +57,7 @@android:background="?attr/selectableItemBackground"android:paddingTop="4dp"android:paddingBottom="4dp"- android:textSize="14sp"+ android:textSize="@dimen/text_body"android:visibility="gone" /><!-- Visual style: hot / cold signal dial and the match's confidence ring -->@@ -97,7 +97,7 @@android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="--"- android:textSize="34sp"+ android:textSize="@dimen/text_display"android:textStyle="bold" /><TextView@@ -106,14 +106,7 @@android:layout_height="wrap_content"android:layout_marginStart="12dp"android:layout_weight="1"- android:textSize="13sp" />-- <com.google.android.material.button.MaterialButton- android:id="@+id/locateButton"- style="@style/Widget.MaterialComponents.Button.OutlinedButton"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="Locate" />+ android:textSize="@dimen/text_body" /></LinearLayout><com.rfsentinel.app.ui.SignalGraphView@@ -122,18 +115,37 @@android:layout_height="140dp"android:layout_marginTop="8dp" />- <!-- Actions -->- <com.google.android.material.chip.ChipGroup- android:id="@+id/actions"+ <!-- The two main actions up front, side by side (same height when a label wraps) -->+ <LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"- android:layout_marginTop="8dp">+ android:layout_marginTop="8dp"+ android:baselineAligned="false"+ android:orientation="horizontal">- <com.google.android.material.chip.Chip+ <com.google.android.material.button.MaterialButton+ android:id="@+id/locateButton"+ android:layout_width="0dp"+ android:layout_height="match_parent"+ android:layout_marginEnd="8dp"+ android:layout_weight="1"+ android:text="Locate" />++ <com.google.android.material.button.MaterialButtonandroid:id="@+id/actionWatchlist"- android:layout_width="wrap_content"- android:layout_height="wrap_content"+ style="@style/Widget.MaterialComponents.Button.OutlinedButton"+ android:layout_width="0dp"+ android:layout_height="match_parent"+ android:layout_weight="1"android:text="Add to watchlist" />+ </LinearLayout>++ <!-- The other actions -->+ <com.google.android.material.chip.ChipGroup+ android:id="@+id/actions"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginTop="4dp"><com.google.android.material.chip.Chipandroid:id="@+id/actionWhitelist"@@ -184,7 +196,7 @@android:layout_height="wrap_content"android:layout_marginTop="16dp"android:text="Everything on this screen comes from signals the device broadcasts publicly. RF Sentinel never connects to it. Distance is a rough estimate from signal strength."- android:textColor="#888888"- android:textSize="11sp" />+ android:textColor="?android:attr/textColorSecondary"+ android:textSize="@dimen/text_caption" /></LinearLayout></ScrollView>diff --git a/app/src/main/res/layout/activity_device_history.xml b/app/src/main/res/layout/activity_device_history.xmlindex c1e7254..79b39d7 100644--- a/app/src/main/res/layout/activity_device_history.xml+++ b/app/src/main/res/layout/activity_device_history.xml@@ -57,7 +57,7 @@android:layout_gravity="center"android:gravity="center"android:padding="24dp"- android:textColor="#888888"+ android:textColor="?android:attr/textColorSecondary"android:visibility="gone" /></FrameLayout>@@ -68,6 +68,6 @@android:layout_height="wrap_content"android:paddingTop="6dp"android:paddingBottom="8dp"- android:textColor="#888888"- android:textSize="12sp" />+ 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.xmlindex 82217f4..ea59d74 100644--- a/app/src/main/res/layout/activity_log.xml+++ b/app/src/main/res/layout/activity_log.xml@@ -16,6 +16,6 @@android:layout_gravity="center"android:gravity="center"android:padding="24dp"- android:textColor="#888888"+ android:textColor="?android:attr/textColorSecondary"android:text="No watchlist matches logged yet." /></FrameLayout>diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xmlindex 3d28fb5..95b2d0e 100644--- a/app/src/main/res/layout/activity_main.xml+++ b/app/src/main/res/layout/activity_main.xml@@ -45,7 +45,7 @@android:paddingEnd="12dp"android:paddingBottom="6dp"android:textColor="#FFFFFF"- android:textSize="14sp"+ android:textSize="@dimen/text_body"android:textStyle="bold"android:visibility="gone" />@@ -55,7 +55,7 @@android:layout_height="wrap_content"android:paddingBottom="4dp"android:text="Idle"- android:textSize="15sp" />+ android:textSize="@dimen/text_subtitle" /><LinearLayoutandroid:layout_width="match_parent"@@ -263,7 +263,7 @@android:gravity="center"android:padding="24dp"android:text="No devices heard yet.\nTap a device for full details.\nLong-press for quick actions (watchlist, whitelist, favorite)."- android:textColor="#888888" />+ android:textColor="?android:attr/textColorSecondary" /><!-- Scrolled down when a new alert arrives above: tap to go up to it. --><TextView@@ -278,7 +278,7 @@android:paddingEnd="14dp"android:paddingBottom="6dp"android:text="▲ New alert"- android:textSize="14sp"+ android:textSize="@dimen/text_body"android:textStyle="bold"android:visibility="gone" /></FrameLayout>diff --git a/app/src/main/res/layout/activity_oui_list.xml b/app/src/main/res/layout/activity_oui_list.xmlindex faea23f..95795f7 100644--- a/app/src/main/res/layout/activity_oui_list.xml+++ b/app/src/main/res/layout/activity_oui_list.xml@@ -1,41 +1,27 @@<?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:padding="16dp">- <RadioGroup- android:id="@+id/ruleType"+ <!-- What the rule matches: one dropdown instead of a row of radio buttons, so every type fits any width -->+ <com.google.android.material.textfield.TextInputLayout+ android:id="@+id/ruleTypeLayout"+ style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"android:layout_width="match_parent"android:layout_height="wrap_content"- android:checkedButton="@id/typeAddress"- android:orientation="horizontal">+ android:hint="Rule type"+ app:endIconMode="dropdown_menu">- <RadioButton- android:id="@+id/typeAddress"- android:layout_width="wrap_content"+ <AutoCompleteTextView+ android:id="@+id/ruleType"+ android:layout_width="match_parent"android:layout_height="wrap_content"- android:text="Address" />-- <RadioButton- android:id="@+id/typeName"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="Name has" />-- <RadioButton- android:id="@+id/typeVendor"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="Maker has" />-- <RadioButton- android:id="@+id/typeProbe"- android:layout_width="wrap_content"- android:layout_height="wrap_content"- android:text="Asks for" />- </RadioGroup>+ android:inputType="none"+ android:saveEnabled="false" />+ </com.google.android.material.textfield.TextInputLayout><EditTextandroid:id="@+id/prefixInput"@@ -49,7 +35,7 @@android:id="@+id/labelInput"android:layout_width="match_parent"android:layout_height="wrap_content"- android:hint="Label (what it is)"+ android:hint="Label: what it is"android:importantForAutofill="no"android:inputType="text" />@@ -64,8 +50,8 @@android:layout_height="wrap_content"android:paddingTop="4dp"android:text="Built-in presets (body cams, Flock, Motorola...) are listed below with their confidence. Payload signatures (Axon tags, Remote ID, trackers, glasses) are built into the detection engine - see About & sources."- android:textColor="#888888"- android:textSize="11sp" />+ android:textColor="?android:attr/textColorSecondary"+ android:textSize="@dimen/text_caption" /><androidx.recyclerview.widget.RecyclerViewandroid:id="@+id/recyclerView"diff --git a/app/src/main/res/layout/activity_probe_list.xml b/app/src/main/res/layout/activity_probe_list.xmlindex ca12cef..bd68859 100644--- a/app/src/main/res/layout/activity_probe_list.xml+++ b/app/src/main/res/layout/activity_probe_list.xml@@ -17,8 +17,8 @@android:layout_height="wrap_content"android:paddingTop="2dp"android:paddingBottom="8dp"- android:textSize="12sp"- android:textColor="#888888"+ android:textSize="@dimen/text_caption"+ android:textColor="?android:attr/textColorSecondary"android:text="Phones and laptops ask by name for WiFi networks they joined before. A USB WiFi adapter or an ESP32 Marauder board hears these requests. Kept only on this phone; a map trace recording always keeps them, with the trace. Tap a name to watch it: you get an alert whenever a device asks for it." /><EditTextdiff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xmlindex bdda241..e532b33 100644--- a/app/src/main/res/layout/activity_settings.xml+++ b/app/src/main/res/layout/activity_settings.xml@@ -141,7 +141,7 @@android:id="@+id/wifiThrottleText"style="@style/SettingsLabel"android:paddingTop="2dp"- android:textSize="12sp" />+ android:textSize="@dimen/text_caption" /><Buttonandroid:id="@+id/wifiThrottleButton"@@ -178,7 +178,7 @@android:id="@+id/carDevicesText"style="@style/SettingsLabel"android:paddingTop="2dp"- android:textSize="12sp" />+ android:textSize="@dimen/text_caption" /><Buttonandroid:id="@+id/carDevicesButton"@@ -360,7 +360,7 @@android:id="@+id/voiceText"style="@style/SettingsLabel"android:paddingTop="0dp"- android:textSize="12sp" />+ android:textSize="@dimen/text_caption" /></LinearLayout><!-- ================= Over other apps ================= -->@@ -433,7 +433,7 @@android:id="@+id/trackerIgnoreText"style="@style/SettingsLabel"android:paddingTop="4dp"- android:textSize="12sp" />+ android:textSize="@dimen/text_caption" /><Buttonandroid:id="@+id/trackerIgnoreButton"@@ -612,7 +612,7 @@android:id="@+id/prefetchCamerasText"style="@style/SettingsLabel"android:paddingTop="0dp"- android:textSize="12sp" />+ android:textSize="@dimen/text_caption" /><Buttonandroid:id="@+id/deflockButton"@@ -625,14 +625,14 @@android:id="@+id/deflockText"style="@style/SettingsLabel"android:paddingTop="0dp"- android:textSize="12sp" />+ android:textSize="@dimen/text_caption" /><!-- Cameras silenced from the map (tap a camera > Ignore alerts). --><TextViewandroid:id="@+id/ignoredCamerasText"style="@style/SettingsLabel"android:paddingTop="4dp"- android:textSize="12sp" />+ android:textSize="@dimen/text_caption" /><Buttonandroid:id="@+id/ignoredCamerasButton"@@ -803,7 +803,7 @@android:id="@+id/liveExportText"style="@style/SettingsLabel"android:paddingTop="0dp"- android:textSize="12sp" />+ android:textSize="@dimen/text_caption" /><TextView android:id="@+id/retentionLabel" style="@style/SettingsLabel" android:text="Keep history for" />diff --git a/app/src/main/res/layout/activity_setup.xml b/app/src/main/res/layout/activity_setup.xmlindex 1427d2c..298da04 100644--- a/app/src/main/res/layout/activity_setup.xml+++ b/app/src/main/res/layout/activity_setup.xml@@ -10,7 +10,7 @@android:layout_width="match_parent"android:layout_height="wrap_content"android:textColor="?attr/colorSecondary"- android:textSize="13sp"+ android:textSize="@dimen/text_body"android:textStyle="bold" /><com.google.android.material.progressindicator.LinearProgressIndicator@@ -25,7 +25,7 @@android:id="@+id/titleText"android:layout_width="match_parent"android:layout_height="wrap_content"- android:textSize="24sp"+ android:textSize="@dimen/text_headline"android:textStyle="bold" /><TextView@@ -34,7 +34,7 @@android:layout_height="wrap_content"android:layout_marginTop="6dp"android:layout_marginBottom="12dp"- android:textSize="14sp" />+ android:textSize="@dimen/text_body" /><ScrollViewandroid:id="@+id/pageScroll"diff --git a/app/src/main/res/layout/activity_wifi_analyzer.xml b/app/src/main/res/layout/activity_wifi_analyzer.xmlindex 02c026b..8c8e271 100644--- a/app/src/main/res/layout/activity_wifi_analyzer.xml+++ b/app/src/main/res/layout/activity_wifi_analyzer.xml@@ -49,7 +49,7 @@android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="8dp"- android:textSize="13sp" />+ android:textSize="@dimen/text_body" /><androidx.recyclerview.widget.RecyclerViewandroid:id="@+id/recyclerView"diff --git a/app/src/main/res/layout/dialog_add_watchlist.xml b/app/src/main/res/layout/dialog_add_watchlist.xmlindex 5d5ff83..53ce26e 100644--- a/app/src/main/res/layout/dialog_add_watchlist.xml+++ b/app/src/main/res/layout/dialog_add_watchlist.xml@@ -34,8 +34,24 @@android:layout_width="match_parent"android:layout_height="wrap_content"android:visibility="gone" />++ <RadioButton+ android:id="@+id/scopeStarts"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:visibility="gone" /></RadioGroup>+ <EditText+ android:id="@+id/startsInput"+ android:layout_width="match_parent"+ android:layout_height="wrap_content"+ android:layout_marginStart="32dp"+ android:hint="Start of the name"+ android:importantForAutofill="no"+ android:inputType="text|textNoSuggestions"+ android:visibility="gone" />+<TextViewandroid:id="@+id/warningText"android:layout_width="match_parent"@@ -43,7 +59,7 @@android:paddingTop="4dp"android:paddingBottom="4dp"android:textColor="@color/match_tag_bg"- android:textSize="12sp"+ android:textSize="@dimen/text_caption"android:visibility="gone" /><EditTextdiff --git a/app/src/main/res/layout/item_detection.xml b/app/src/main/res/layout/item_detection.xmlindex 850c44a..da9a750 100644--- a/app/src/main/res/layout/item_detection.xml+++ b/app/src/main/res/layout/item_detection.xml@@ -10,21 +10,21 @@android:layout_width="match_parent"android:layout_height="wrap_content"android:textStyle="bold"- android:textSize="15sp" />+ android:textSize="@dimen/text_subtitle" /><TextViewandroid:id="@+id/macText"android:layout_width="match_parent"android:layout_height="wrap_content"- android:textSize="13sp"+ android:textSize="@dimen/text_body"android:fontFamily="monospace" /><TextViewandroid:id="@+id/metaText"android:layout_width="match_parent"android:layout_height="wrap_content"- android:textSize="12sp"- android:textColor="#888888" />+ android:textSize="@dimen/text_caption"+ android:textColor="?android:attr/textColorSecondary" /><Viewandroid:layout_width="match_parent"diff --git a/app/src/main/res/layout/item_device.xml b/app/src/main/res/layout/item_device.xmlindex d1ab5e1..d2b70fd 100644--- a/app/src/main/res/layout/item_device.xml+++ b/app/src/main/res/layout/item_device.xml@@ -31,7 +31,7 @@android:paddingTop="1dp"android:paddingBottom="1dp"android:textColor="@android:color/white"- android:textSize="11sp"+ android:textSize="@dimen/text_caption"android:textStyle="bold"android:visibility="gone" />@@ -47,21 +47,21 @@android:id="@+id/titleText"android:layout_width="match_parent"android:layout_height="wrap_content"- android:textSize="15sp" />+ android:textSize="@dimen/text_subtitle" /><TextViewandroid:id="@+id/macText"android:layout_width="match_parent"android:layout_height="wrap_content"android:fontFamily="monospace"- android:textSize="13sp" />+ android:textSize="@dimen/text_body" /><TextViewandroid:id="@+id/metaText"android:layout_width="match_parent"android:layout_height="wrap_content"- android:textColor="#888888"- android:textSize="12sp" />+ android:textColor="?android:attr/textColorSecondary"+ android:textSize="@dimen/text_caption" /></LinearLayout><!-- Visual style: signal bars -->@@ -84,8 +84,8 @@android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginTop="2dp"- android:textColor="#888888"- android:textSize="10sp" />+ android:textColor="?android:attr/textColorSecondary"+ android:textSize="@dimen/text_caption" /></LinearLayout></LinearLayout>diff --git a/app/src/main/res/layout/item_oui_entry.xml b/app/src/main/res/layout/item_oui_entry.xmlindex a907e12..fcbd5c0 100644--- a/app/src/main/res/layout/item_oui_entry.xml+++ b/app/src/main/res/layout/item_oui_entry.xml@@ -23,14 +23,14 @@android:id="@+id/labelText"android:layout_width="match_parent"android:layout_height="wrap_content"- android:textSize="13sp" />+ android:textSize="@dimen/text_body" /><TextViewandroid:id="@+id/confidenceText"android:layout_width="match_parent"android:layout_height="wrap_content"- android:textSize="11sp"- android:textColor="#888888" />+ android:textSize="@dimen/text_caption"+ android:textColor="?android:attr/textColorSecondary" /></LinearLayout><Buttondiff --git a/app/src/main/res/layout/item_probe.xml b/app/src/main/res/layout/item_probe.xmlindex a0e37da..3220723 100644--- a/app/src/main/res/layout/item_probe.xml+++ b/app/src/main/res/layout/item_probe.xml@@ -23,8 +23,8 @@android:id="@+id/metaText"android:layout_width="match_parent"android:layout_height="wrap_content"- android:textSize="12sp"- android:textColor="#888888" />+ android:textSize="@dimen/text_caption"+ android:textColor="?android:attr/textColorSecondary" /></LinearLayout><Buttondiff --git a/app/src/main/res/layout/item_whitelist.xml b/app/src/main/res/layout/item_whitelist.xmlindex 765d4c8..9830265 100644--- a/app/src/main/res/layout/item_whitelist.xml+++ b/app/src/main/res/layout/item_whitelist.xml@@ -23,8 +23,8 @@android:id="@+id/noteText"android:layout_width="match_parent"android:layout_height="wrap_content"- android:textSize="12sp"- android:textColor="#888888" />+ android:textSize="@dimen/text_caption"+ android:textColor="?android:attr/textColorSecondary" /></LinearLayout><Buttondiff --git a/app/src/main/res/menu/menu_main.xml b/app/src/main/res/menu/menu_main.xmlindex 8cf2a26..7c90b4b 100644--- a/app/src/main/res/menu/menu_main.xml+++ b/app/src/main/res/menu/menu_main.xml@@ -19,11 +19,16 @@app:showAsAction="always" /><item android:id="@+id/action_waze_now" android:title="Check Waze now" app:showAsAction="never" /><item android:id="@+id/action_waze_status" android:title="Waze status" app:showAsAction="never" />- <item android:id="@+id/action_device_history" android:title="Device history (search)" app:showAsAction="never" />- <item android:id="@+id/action_match_log" android:title="Match history" app:showAsAction="never" />- <item android:id="@+id/action_traces" android:title="Recorded traces" app:showAsAction="never" />- <item android:id="@+id/action_history" android:title="History map & timeline" app:showAsAction="never" />- <item android:id="@+id/action_probes" android:title="Requested networks" app:showAsAction="never" />+ <!-- Everything the app remembers, in one place. -->+ <item android:id="@+id/action_history_menu" android:title="History" app:showAsAction="never">+ <menu>+ <item android:id="@+id/action_device_history" android:title="Device history" />+ <item android:id="@+id/action_match_log" android:title="Match history" />+ <item android:id="@+id/action_traces" android:title="Recorded traces" />+ <item android:id="@+id/action_history" android:title="History map & timeline" />+ <item android:id="@+id/action_probes" android:title="Requested networks" />+ </menu>+ </item>- <item android:id="@+id/action_export" android:title="Export (history, matches, everything)..." app:showAsAction="never" />+ <item android:id="@+id/action_export" android:title="Export..." app:showAsAction="never" /></menu>diff --git a/app/src/main/res/values/dimens.xml b/app/src/main/res/values/dimens.xmlnew file mode 100644index 0000000..abf541e--- /dev/null+++ b/app/src/main/res/values/dimens.xml@@ -0,0 +1,13 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <!--+ The app's type scale: every screen picks one of these, so the same kind of text is the same size+ everywhere. The map's driving overlay and the home-screen widget keep their own sizes for glancing.+ -->+ <dimen name="text_caption">12sp</dimen> <!-- hints, timestamps, small print -->+ <dimen name="text_body">14sp</dimen> <!-- normal text, secondary lines -->+ <dimen name="text_subtitle">16sp</dimen> <!-- list item titles, emphasised lines -->+ <dimen name="text_title">20sp</dimen> <!-- screen and card titles -->+ <dimen name="text_headline">24sp</dimen> <!-- big headings -->+ <dimen name="text_display">34sp</dimen> <!-- one big number -->+</resources>diff --git a/app/src/main/res/values/ids.xml b/app/src/main/res/values/ids.xmlindex 2dfaeb2..47f13fc 100644--- a/app/src/main/res/values/ids.xml+++ b/app/src/main/res/values/ids.xml@@ -2,4 +2,6 @@<resources><item name="mapHost" type="id" /><item name="visual_chip_color" type="id" />+ <!-- Settings rows the search hid (so clearing it shows only those again) -->+ <item name="search_hidden" type="id" /></resources>diff --git a/app/src/test/java/com/rfsentinel/app/oui/ProbeRuleTest.kt b/app/src/test/java/com/rfsentinel/app/oui/ProbeRuleTest.ktindex 2227906..057cfe4 100644--- a/app/src/test/java/com/rfsentinel/app/oui/ProbeRuleTest.kt+++ b/app/src/test/java/com/rfsentinel/app/oui/ProbeRuleTest.kt@@ -18,6 +18,15 @@ class ProbeRuleTest {assertTrue(OuiEntry("fp:a1b2c3d4", "x").isFingerprintRule)}+ @Test+ fun ssidPrefixRulesAreValidKeys() {+ assertTrue(OuiWatchlist.isValidKey("starts:Flock-"))+ assertFalse(OuiWatchlist.isValidKey("starts: "))+ assertEquals("starts:Flock-", OuiWatchlist.normalizeKey("STARTS: Flock- "))+ assertTrue(OuiEntry("starts:Flock-", "x").isStartsRule)+ assertFalse(OuiEntry("starts:Flock-", "x").isNameRule)+ }+@Testfun aRequestForAWatchedNameIsAnAlertHit() {val rule = OuiEntry("probe:PD-MDT", "Police laptop", "user-added", "custom")diff --git a/app/src/test/java/com/rfsentinel/app/ui/AlertCardTest.kt b/app/src/test/java/com/rfsentinel/app/ui/AlertCardTest.ktindex cb43f97..6a28aee 100644--- a/app/src/test/java/com/rfsentinel/app/ui/AlertCardTest.kt+++ b/app/src/test/java/com/rfsentinel/app/ui/AlertCardTest.kt@@ -12,7 +12,6 @@ import com.rfsentinel.app.detect.Categoryimport com.rfsentinel.app.util.Prefsimport org.junit.Afterimport org.junit.Assert.assertEquals-import org.junit.Assert.assertFalseimport org.junit.Assert.assertNullimport org.junit.Assert.assertTrueimport org.junit.Before@@ -125,10 +124,11 @@ class AlertCardTest {}@Test- fun aSnoozedAlertStaysOffTheMap() {+ fun aSnoozedAlertStillShowsOnTheMap() {+ // Snooze only silences sound and voice: the card still shows, silently.Prefs.setAlertsSnoozedUntil(activity, System.currentTimeMillis() + 60_000L)card.show(alert())- assertFalse(b.alertCard.visibility == View.VISIBLE)+ assertEquals(View.VISIBLE, b.alertCard.visibility)}@Testdiff --git a/app/src/test/java/com/rfsentinel/app/util/DeviceExportTest.kt b/app/src/test/java/com/rfsentinel/app/util/DeviceExportTest.ktindex 49ec455..aff81d1 100644--- a/app/src/test/java/com/rfsentinel/app/util/DeviceExportTest.kt+++ b/app/src/test/java/com/rfsentinel/app/util/DeviceExportTest.kt@@ -114,4 +114,16 @@ class DeviceExportTest {assertEquals(701, all["matchLog"].asJsonArray.size())assertEquals(listOf("exportedBy", "exportedAt", "sessionDevices", "deviceHistory", "matchLog", "watchlist"), all.keySet().toList())}++ /** The history export on its own, streamed a batch at a time: the same CSV as the one-shot one, and every row in the JSON. */+ @Test+ fun historyExportIsStreamedInBatches() {+ val hist = (0 until 1203).map { KnownDeviceEntity("AA:BB:CC:%02X:%02X:%02X".format(it shr 16, (it shr 8) and 0xff, it and 0xff), 1000, 2000L - it, 1, 1, "n$it", null, null) }+ fun streamed(csv: Boolean) = java.io.StringWriter().also { out ->+ kotlinx.coroutines.runBlocking { DeviceExport.writeHistory(out, csv, DeviceExport.batches(hist)) }+ }.toString()+ assertEquals(DeviceExport.historyCsv(hist), streamed(csv = true))+ val json = JsonParser.parseString(streamed(csv = false)).asJsonArray+ assertEquals(hist.map { it.mac }, json.map { it.asJsonObject["mac"].asString })+ }}