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
Main screen, visual style: counts on the filter chips, hardware folded into a strip, slim All clear bar
CIS-C07ae3d3860291
diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.ktindex 077a6f2..f28d373 100644--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt@@ -61,9 +61,7 @@ class MainActivity : AppCompatActivity() {private var query = ""private var deviceCount = 0private var flaggedCount = 0- private var bleCount = 0- private var wifiCount = 0- /** The visual style's status: counters and hardware cards (Settings > Appearance). */+ /** The visual style's status: warning chip and hardware strip (Settings > Appearance). */private val statusPanel by lazy { com.rfsentinel.app.ui.StatusPanel(this) }private var demoMode = false@@ -288,6 +286,36 @@ class MainActivity : AppCompatActivity() {}}+ /**+ * Visual style: the filter chips are tinted pills, shorter than the stock ones, [color] when set (the+ * flagged count in red). The list style keeps the outlined chips.+ */+ private fun styleFilterChip(chip: com.google.android.material.chip.Chip, visual: Boolean, color: Int?) {+ val key = if (visual) "v${color ?: 0}" else "list"+ if (chip.getTag(R.id.visual_chip_color) == key) return+ chip.setTag(R.id.visual_chip_color, key)+ val dp = resources.displayMetrics.density+ com.rfsentinel.app.ui.ChipStyle.apply(chip)+ if (!visual) {+ chip.chipMinHeight = 32 * dp+ chip.setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, 14f)+ return+ }+ // No invisible 48 dp touch frame in the visual style: the row is 16 dp shorter.+ chip.setEnsureMinTouchTargetSize(false)+ val (accent, onAccent) = com.rfsentinel.app.ui.ChipStyle.accent(this)+ val c = color ?: accent+ val checked = intArrayOf(android.R.attr.state_checked)+ val none = intArrayOf()+ chip.chipBackgroundColor = android.content.res.ColorStateList(arrayOf(checked, none),+ intArrayOf(c, com.rfsentinel.app.ui.VisualMode.tint(c, 0x26)))+ chip.chipStrokeColor = android.content.res.ColorStateList(arrayOf(checked, none), intArrayOf(c, com.rfsentinel.app.ui.VisualMode.tint(c, 0x99)))+ chip.chipStrokeWidth = 1.2f * dp+ chip.setTextColor(android.content.res.ColorStateList(arrayOf(checked, none), intArrayOf(onAccent, c)))+ chip.chipMinHeight = 28 * dp+ chip.setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, 13f)+ }+/** List / radar toggle: the selected half filled with the theme highlight. */private fun styleViewToggle() {val (accent, onAccent) = com.rfsentinel.app.ui.ChipStyle.accent(this)@@ -346,7 +374,7 @@ class MainActivity : AppCompatActivity() {com.rfsentinel.app.sdr.RadioReference.status.takeIf { it.isNotBlank() && com.rfsentinel.app.util.Prefs.radioReferenceOn(this) }?.let { com.rfsentinel.app.ui.StatusPanel.Hardware(it) })- statusPanel.update(running, bleCount, wifiCount, liveCellCount(now), flaggedCount, warning, hardware)+ statusPanel.update(running, warning, hardware)return}binding.statusText.text = when {@@ -498,8 +526,6 @@ class MainActivity : AppCompatActivity() {val threshold = Prefs.alertThreshold(this)binding.wazeSwipe.isEnabled = com.rfsentinel.app.ui.WazeUi.on(this) && panes.listShowndeviceCount = all.size- bleCount = all.count { Advert.Source.BLE in it.sources }- wifiCount = all.count { Advert.Source.WIFI in it.sources }adapter.visual = com.rfsentinel.app.ui.VisualMode.on(this, com.rfsentinel.app.ui.VisualMode.Screen.DEVICE_LIST)// The banner and radar alert only for flagged devices still in range.val flagged = all.filter { com.rfsentinel.app.ui.LiveWindow.alerting(it, now) }@@ -508,6 +534,7 @@ class MainActivity : AppCompatActivity() {updateStatus()// Live counts on the chips ("Trackers 2"); empty filters stay unlabelled.+ val visualChips = com.rfsentinel.app.ui.VisualMode.on(this, com.rfsentinel.app.ui.VisualMode.Screen.STATUS)for ((f, chip) in filterChips) {val n = when (f) {com.rfsentinel.app.ui.DeviceFilter.CELLS -> liveCellCount(now)@@ -517,6 +544,7 @@ class MainActivity : AppCompatActivity() {}val label = if (f == com.rfsentinel.app.ui.DeviceFilter.ALL || n > 0) "${f.label} $n" else f.labelif (chip.text != label) chip.text = label+ styleFilterChip(chip, visualChips, if (f == com.rfsentinel.app.ui.DeviceFilter.FLAGGED && n > 0) 0xFFD0503C.toInt() else null)}val visible = all.filter { filter.matches(it) && matchesQuery(it) }.sortedWith(@@ -776,6 +804,7 @@ class MainActivity : AppCompatActivity() {ambient.score >= threshold -> 0xFFC8431A.toInt()else -> WEAK_COLOR})+ slimBanner(false)return}val (color, text) = when {@@ -787,6 +816,19 @@ class MainActivity : AppCompatActivity() {}banner.text = if (flagged.size > 1 && following == null) "$text (+${flagged.size - 1} more)" else textbanner.background.mutate().setTint(color)+ slimBanner(top == null && following == null)+ }++ /** Visual style: "All clear" is a slim bar, so the map and list get the room; an alert gets the full size. */+ private fun slimBanner(allClear: Boolean) {+ val slim = allClear && com.rfsentinel.app.ui.VisualMode.on(this, com.rfsentinel.app.ui.VisualMode.Screen.STATUS)+ val banner = binding.threatBanner+ if (banner.getTag(R.id.visual_chip_color) == slim) return+ banner.setTag(R.id.visual_chip_color, slim)+ val dp = resources.displayMetrics.density+ val v = ((if (slim) 2 else 6) * dp).toInt()+ banner.setPadding((12 * dp).toInt(), v, (12 * dp).toInt(), v)+ banner.textSize = if (slim) 12f else 14f}private fun bandOrder(band: String) = when (band) {diff --git a/app/src/main/java/com/rfsentinel/app/ui/StatusPanel.kt b/app/src/main/java/com/rfsentinel/app/ui/StatusPanel.ktindex beb98a1..0ed7ecb 100644--- a/app/src/main/java/com/rfsentinel/app/ui/StatusPanel.kt+++ b/app/src/main/java/com/rfsentinel/app/ui/StatusPanel.kt@@ -5,13 +5,16 @@ import android.graphics.Typefaceimport android.graphics.drawable.GradientDrawableimport android.view.Gravityimport android.view.View+import android.widget.HorizontalScrollViewimport android.widget.LinearLayoutimport android.widget.TextView/**- * The main screen's status in the visual style: counters for what's heard (Bluetooth, WiFi, cells,- * flagged), a warning chip when there is one, and a card per piece of USB / ESP32 hardware with a- * coloured dot for its state and, for the WiFi adapter and the RTL-SDR, a line of its packets per second.+ * The main screen's status in the visual style: a warning chip when there is one, and the USB / ESP32+ * hardware. The hardware starts folded into one thin strip of chips (a coloured dot for its state and,+ * for the WiFi adapter and the RTL-SDR, its packets per second); tap the strip to unfold a card per+ * device with a line of its rate. ✕ hides the hardware until one of them changes state.+ * The device counts are on the filter chips below.*/class StatusPanel(private val context: Context) {@@ -19,53 +22,68 @@ class StatusPanel(private val context: Context) {class Hardware(val status: String, val counter: (() -> Long)? = null, val unit: String = "/s")private val dp = context.resources.displayMetrics.density- private val accent = ChipStyle.accent(context).first+ private val prefs = context.getSharedPreferences("rf_sentinel_prefs", Context.MODE_PRIVATE)+ private var folded: Boolean+ get() = prefs.getBoolean("status_hw_folded", true)+ set(v) { prefs.edit().putBoolean("status_hw_folded", v).apply() }+ /** The hardware states when ✕ was tapped; the strip comes back when they change. */+ private var hiddenAt: String?+ get() = prefs.getString("status_hw_hidden", null)+ set(v) { prefs.edit().putString("status_hw_hidden", v).apply() }+val root = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL; visibility = View.GONE }- private val counters = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL }private val note = TextView(context).apply { textSize = 12f; visibility = View.GONE }+ private val strip = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL }+ private val chipScroll = HorizontalScrollView(context).apply { isHorizontalScrollBarEnabled = false }+ private val chips = LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL }+ private val title = TextView(context).apply {+ text = "External hardware"; textSize = 12f; setTypeface(typeface, Typeface.BOLD); alpha = 0.8f+ setPadding((4 * dp).toInt(), 0, 0, 0)+ }+ private val foldButton = iconButton("▾", "Show the hardware details")+ private val hideButton = iconButton("✕", "Hide the hardware status until something changes")private val cards = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL }- private val counterViews = List(4) { pill() }/** Per hardware name: the counter's last reading and its rate over the last minute. */private class Rate(var last: Long = -1, var at: Long = 0, val history: ArrayDeque<Float> = ArrayDeque())private val rates = HashMap<String, Rate>()private var cardKey = ""+ private var last: List<Hardware> = emptyList()init {- counterViews.forEachIndexed { i, v ->- // A fixed height so the text can shrink to fit narrow screens ("Flagged 12" on a small phone).- counters.addView(v, LinearLayout.LayoutParams(0, (26 * dp).toInt(), 1f).apply { if (i > 0) marginStart = (5 * dp).toInt() })- }- root.addView(counters)- root.addView(note, LinearLayout.LayoutParams(-1, -2).apply { topMargin = (5 * dp).toInt() })+ chipScroll.addView(chips)+ strip.addView(chipScroll, LinearLayout.LayoutParams(0, -2, 1f))+ strip.addView(title, LinearLayout.LayoutParams(0, -2, 1f))+ strip.addView(foldButton)+ strip.addView(hideButton)+ // The whole strip folds and unfolds; the chips scroll sideways when there are many.+ val toggle = View.OnClickListener { folded = !folded; showHardware(last) }+ strip.setOnClickListener(toggle)+ chips.setOnClickListener(toggle)+ title.setOnClickListener(toggle)+ foldButton.setOnClickListener(toggle)+ hideButton.setOnClickListener { hiddenAt = signature(last); showHardware(last) }+ root.addView(note, LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = (4 * dp).toInt() })+ root.addView(strip, LinearLayout.LayoutParams(-1, -2))root.addView(cards)- root.setPadding(0, 0, 0, (6 * dp).toInt())+ root.setPadding(0, 0, 0, (4 * dp).toInt())}- private fun pill() = TextView(context).apply {- textSize = 12f- setTypeface(typeface, Typeface.BOLD)+ private fun iconButton(text: String, description: String) = TextView(context).apply {+ this.text = text+ contentDescription = description+ textSize = 14fgravity = Gravity.CENTER- maxLines = 1- androidx.core.widget.TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(this, 8, 12, 1, android.util.TypedValue.COMPLEX_UNIT_SP)+ alpha = 0.8f+ minWidth = (36 * dp).toInt()+ minHeight = (32 * dp).toInt()+ isClickable = true+ isFocusable = true}- private fun setPill(v: TextView, text: String, color: Int) {- if (v.text != text) v.text = text- VisualMode.chip(v, color)- v.setPadding((4 * dp).toInt(), (2 * dp).toInt(), (4 * dp).toInt(), (2 * dp).toInt())- }-- /**- * [running]: scanning; [ble], [wifi], [cells], [flagged]: what's heard now; [warning]: a fake-cell or- * restarted-scan note; [hardware]: the non-blank hardware status lines.- */- fun update(running: Boolean, ble: Int, wifi: Int, cells: Int, flagged: Int, warning: String?, hardware: List<Hardware>) {+ /** [running]: scanning; [warning]: a fake-cell or restarted-scan note; [hardware]: the non-blank hardware status lines. */+ fun update(running: Boolean, warning: String?, hardware: List<Hardware>) {val grey = (ChipStyle.onSurface(context) and 0x00FFFFFF) or 0x99000000.toInt()- setPill(counterViews[0], "BLE $ble", if (running) accent else grey)- setPill(counterViews[1], "WiFi $wifi", if (running) accent else grey)- setPill(counterViews[2], "Cells $cells", if (running) accent else grey)- setPill(counterViews[3], "Flagged $flagged", if (flagged > 0) 0xFFD0503C.toInt() else if (running) accent else grey)val shown = if (!running) "Idle - tap Start to listen for nearby devices" else warning?.let { "⚠ $it" }note.visibility = if (shown != null) View.VISIBLE else View.GONEif (shown != null) {@@ -76,21 +94,65 @@ class StatusPanel(private val context: Context) {}private fun showHardware(list: List<Hardware>) {+ last = listval now = System.currentTimeMillis()+ val sig = signature(list)+ hiddenAt?.let { if (it != sig && list.isNotEmpty()) hiddenAt = null }+ val hidden = list.isEmpty() || hiddenAt == sig+ strip.visibility = if (hidden) View.GONE else View.VISIBLE+ val rateText = list.associate { h -> name(h.status) to sample(h, now) }+ val unfolded = !hidden && !folded+ cards.visibility = if (unfolded) View.VISIBLE else View.GONE+ chipScroll.visibility = if (unfolded) View.GONE else View.VISIBLE+ title.visibility = if (unfolded) View.VISIBLE else View.GONE+ VisualMode.text(foldButton, if (unfolded) "▴" else "▾")+ foldButton.contentDescription = if (unfolded) "Fold the hardware details" else "Show the hardware details"+ if (hidden) return+val key = list.joinToString("|") { name(it.status) }if (key != cardKey) {cardKey = keycards.removeAllViews()- list.forEach { cards.addView(card(), LinearLayout.LayoutParams(-1, -2).apply { topMargin = (5 * dp).toInt() }) }+ chips.removeAllViews()+ list.forEach { _ ->+ cards.addView(card(), LinearLayout.LayoutParams(-1, -2).apply { topMargin = (4 * dp).toInt() })+ chips.addView(TextView(context).apply { textSize = 12f; setTypeface(typeface, Typeface.BOLD); maxLines = 1+ setOnClickListener { folded = !folded; showHardware(last) } },+ LinearLayout.LayoutParams(-2, -2).apply { marginEnd = (6 * dp).toInt() })+ }rates.keys.retainAll(list.map { name(it.status) }.toSet())}- list.forEachIndexed { i, h -> bind(cards.getChildAt(i) as LinearLayout, h, now) }+ list.forEachIndexed { i, h ->+ val color = colorOf(h.status)+ val n = name(h.status)+ val chip = chips.getChildAt(i) as TextView+ VisualMode.text(chip, "● $n" + (rateText[n]?.let { " · $it" } ?: ""))+ VisualMode.chip(chip, color)+ chip.setPadding((8 * dp).toInt(), (3 * dp).toInt(), (8 * dp).toInt(), (3 * dp).toInt())+ if (unfolded) bind(cards.getChildAt(i) as LinearLayout, h, color, rateText[n])+ }+ }++ /** The names and states, to tell when something changed after ✕. */+ private fun signature(list: List<Hardware>) = list.joinToString("|") { name(it.status) + ":" + stateOf(it.status) }++ /** Takes a reading of [h]'s counter about once a second; the latest rate as text, or null without a counter. */+ private fun sample(h: Hardware, now: Long): String? {+ val counter = h.counter ?: return null+ val r = rates.getOrPut(name(h.status)) { Rate() }+ val n = counter()+ if (r.last >= 0 && now - r.at >= 900) {+ r.history.addLast((n - r.last).coerceAtLeast(0) * 1000f / (now - r.at))+ while (r.history.size > 60) r.history.removeFirst()+ }+ if (r.last < 0 || now - r.at >= 900) { r.last = n; r.at = now }+ return r.history.lastOrNull()?.let { "%.0f%s".format(it, h.unit) } ?: "–"}private fun card() = LinearLayout(context).apply {orientation = LinearLayout.HORIZONTALgravity = Gravity.CENTER_VERTICAL- val p = (8 * dp).toInt(); setPadding((10 * dp).toInt(), p, (10 * dp).toInt(), p)+ val p = (6 * dp).toInt(); setPadding((10 * dp).toInt(), p, (10 * dp).toInt(), p)addView(View(context), LinearLayout.LayoutParams((10 * dp).toInt(), (10 * dp).toInt()).apply { marginEnd = (8 * dp).toInt() })addView(LinearLayout(context).apply {orientation = LinearLayout.VERTICAL@@ -106,36 +168,30 @@ class StatusPanel(private val context: Context) {}, LinearLayout.LayoutParams(-2, -2).apply { marginStart = (8 * dp).toInt() })}- private fun bind(card: LinearLayout, h: Hardware, now: Long) {- val color = when (stateOf(h.status)) {- State.ERROR -> 0xFFD0503C.toInt()- State.WAIT -> 0xFFE0A33A.toInt()- State.LIVE -> 0xFF2E9E5B.toInt()+ private fun bind(card: LinearLayout, h: Hardware, color: Int, rate: String?) {+ if (card.getTag(com.rfsentinel.app.R.id.visual_chip_color) != color) {+ card.setTag(com.rfsentinel.app.R.id.visual_chip_color, color)+ card.background = VisualMode.card(context, color, 0x16, 0x66, 12f)+ card.getChildAt(0).background = GradientDrawable().apply { shape = GradientDrawable.OVAL; setColor(color) }}- card.background = VisualMode.card(context, color, 0x16, 0x66, 12f)- card.getChildAt(0).background = GradientDrawable().apply { shape = GradientDrawable.OVAL; setColor(color) }val texts = card.getChildAt(1) as LinearLayout- val name = name(h.status)- VisualMode.text(texts.getChildAt(0) as TextView, name)+ VisualMode.text(texts.getChildAt(0) as TextView, name(h.status))VisualMode.text(texts.getChildAt(1) as TextView, detail(h.status))val side = card.getChildAt(2) as LinearLayout- val counter = h.counter- side.visibility = if (counter != null) View.VISIBLE else View.GONE- if (counter == null) return- // Rate over each refresh, the last minute of it as a line.- val r = rates.getOrPut(name) { Rate() }- val n = counter()- if (r.last >= 0 && now - r.at >= 900) {- r.history.addLast((n - r.last).coerceAtLeast(0) * 1000f / (now - r.at))- while (r.history.size > 60) r.history.removeFirst()- }- if (r.last < 0 || now - r.at >= 900) { r.last = n; r.at = now }- (side.getChildAt(0) as SparklineView).set(r.history.toFloatArray(), color, 5f)- VisualMode.text(side.getChildAt(1) as TextView, r.history.lastOrNull()?.let { "%.0f%s".format(it, h.unit) } ?: "–")+ side.visibility = if (rate != null) View.VISIBLE else View.GONE+ if (rate == null) return+ (side.getChildAt(0) as SparklineView).set(rates[name(h.status)]?.history?.toFloatArray() ?: FloatArray(0), color, 5f)+ VisualMode.text(side.getChildAt(1) as TextView, rate)}private enum class State { LIVE, WAIT, ERROR }+ private fun colorOf(s: String) = when (stateOf(s)) {+ State.ERROR -> 0xFFD0503C.toInt()+ State.WAIT -> 0xFFE0A33A.toInt()+ State.LIVE -> 0xFF2E9E5B.toInt()+ }+private fun stateOf(s: String): State {val l = s.lowercase()return when {diff --git a/app/src/test/java/com/rfsentinel/app/ui/StatusPanelTest.kt b/app/src/test/java/com/rfsentinel/app/ui/StatusPanelTest.ktnew file mode 100644index 0000000..6068718--- /dev/null+++ b/app/src/test/java/com/rfsentinel/app/ui/StatusPanelTest.kt@@ -0,0 +1,73 @@+package com.rfsentinel.app.ui++import android.app.Application+import android.view.View+import android.view.ViewGroup+import android.widget.TextView+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment+import org.robolectric.annotation.Config++/** The main screen's hardware strip: folded by default, unfolds on a tap, ✕ hides it until a state changes. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35], application = Application::class)+class StatusPanelTest {+ private val ctx get() = RuntimeEnvironment.getApplication()++ private fun shownTexts(v: View): List<String> {+ if (v.visibility != View.VISIBLE) return emptyList()+ val own = (v as? TextView)?.let { listOf(it.text.toString()) }.orEmpty()+ return own + if (v is ViewGroup) (0 until v.childCount).flatMap { shownTexts(v.getChildAt(it)) } else emptyList()+ }++ private fun button(v: View, desc: String): View? {+ if (v.contentDescription?.toString() == desc) return v+ if (v is ViewGroup) for (i in 0 until v.childCount) button(v.getChildAt(i), desc)?.let { return it }+ return null+ }++ private val live = listOf(+ StatusPanel.Hardware("OUI-SPY: connecting..."),+ StatusPanel.Hardware("RTL8812BU · live · 32 access points", { 0L }, " frames/s")+ )++ @Test+ fun foldsUnfoldsAndHides() {+ val p = StatusPanel(ctx).also { it.root.visibility = View.VISIBLE }+ p.update(running = true, warning = null, hardware = live)+ var t = shownTexts(p.root)+ assertTrue(t.toString(), t.any { it.startsWith("● OUI-SPY") })+ assertTrue(t.toString(), t.any { it.startsWith("● RTL8812BU") })+ assertFalse("folded: no detail lines", t.any { it.contains("32 access points") })++ button(p.root, "Show the hardware details")!!.performClick()+ t = shownTexts(p.root)+ assertTrue(t.toString(), t.contains("External hardware"))+ assertTrue(t.toString(), t.any { it.contains("32 access points") })++ button(p.root, "Fold the hardware details")!!.performClick()+ assertFalse(shownTexts(p.root).any { it.contains("32 access points") })++ button(p.root, "Hide the hardware status until something changes")!!.performClick()+ p.update(running = true, warning = null, hardware = live)+ assertTrue(shownTexts(p.root).none { it.contains("OUI-SPY") })++ // OUI-SPY goes from connecting to live: the strip is back.+ p.update(running = true, warning = null, hardware = listOf(StatusPanel.Hardware("OUI-SPY: live"), live[1]))+ assertTrue(shownTexts(p.root).any { it.startsWith("● OUI-SPY") })+ }++ @Test+ fun warningAndIdleNote() {+ val p = StatusPanel(ctx).also { it.root.visibility = View.VISIBLE }+ p.update(running = false, warning = null, hardware = emptyList())+ assertEquals(listOf("Idle - tap Start to listen for nearby devices"), shownTexts(p.root))+ p.update(running = true, warning = "Bluetooth scan restarted", hardware = emptyList())+ assertEquals(listOf("⚠ Bluetooth scan restarted"), shownTexts(p.root))+ }+}