Skip to content

RF Sentinel (RFSentinel): free, open-source police detector app for Android. Spots police body cams, Flock ALPR cameras, AirTag trackers, Remote ID drones, smart glasses and fake cell towers from Bluetooth LE and WiFi. No root.

False alerts: log and mute from the device page or long-press, History > False alerts with search and export; Autostart: play a chosen music app when the car's Bluetooth connects

CIS-C0df40d70accf1
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 7d07632..cf3e957 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -54,6 +54,13 @@
<intent>
<action android:name="android.intent.action.TTS_SERVICE" />
</intent>
+ <!-- Music apps for Settings > Autostart > Play music in the car (receiver.CarMusic). -->
+ <intent>
+ <action android:name="android.media.browse.MediaBrowserService" />
+ </intent>
+ <intent>
+ <action android:name="android.intent.action.MEDIA_BUTTON" />
+ </intent>
</queries>
<application
diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
index 2374606..e69af59 100644
--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
@@ -1504,6 +1504,7 @@ class MainActivity : AppCompatActivity() {
R.id.action_waze_status -> { com.rfsentinel.app.ui.WazeUi.openStatus(this); true }
R.id.action_device_history -> { startActivity(Intent(this, com.rfsentinel.app.ui.DeviceHistoryActivity::class.java)); true }
R.id.action_match_log -> { startActivity(Intent(this, DetectionLogActivity::class.java)); true }
+ R.id.action_false_alerts -> { startActivity(Intent(this, DetectionLogActivity::class.java).putExtra(DetectionLogActivity.EXTRA_FALSE_ALERTS, true)); true }
R.id.action_settings -> { startActivity(Intent(this, SettingsActivity::class.java)); true }
R.id.action_watchlist -> { startActivity(Intent(this, com.rfsentinel.app.ouilist.OuiListActivity::class.java)); true }
R.id.action_whitelist -> { startActivity(Intent(this, com.rfsentinel.app.whitelist.WhitelistActivity::class.java)); true }
diff --git a/app/src/main/java/com/rfsentinel/app/data/FalseAlerts.kt b/app/src/main/java/com/rfsentinel/app/data/FalseAlerts.kt
new file mode 100644
index 0000000..d937c86
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/data/FalseAlerts.kt
@@ -0,0 +1,73 @@
+package com.rfsentinel.app.data
+
+import android.content.Context
+import com.google.gson.Gson
+import com.google.gson.reflect.TypeToken
+import com.rfsentinel.app.detect.DeviceIntel
+import com.rfsentinel.app.service.DeviceRegistry
+
+/**
+ * Alerts you marked as false, kept to look at later (History > False alerts) and export, e.g. to fix a signature.
+ * Marking one also mutes the device ([AlertMutes], until you take it off the list).
+ */
+object FalseAlerts {
+
+ /** The match as it was when marked, in the match log's shape so its list and exports are reused, plus your note. */
+ data class Entry(val match: DetectionEntity, val note: String = "")
+
+ private const val PREFS = "false_alerts"
+ private const val KEY = "entries"
+ private val gson = Gson()
+ private val type = object : TypeToken<List<Entry>>() {}.type
+ @Volatile private var entries: List<Entry>? = null
+
+ @Synchronized
+ fun all(context: Context): List<Entry> = entries ?: runCatching {
+ gson.fromJson<List<Entry>>(context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null), type)
+ }.getOrNull().orEmpty().also { entries = it }
+
+ fun contains(context: Context, mac: String) = all(context).any { it.match.mac == mac }
+
+ @Synchronized
+ private fun save(context: Context, list: List<Entry>) {
+ entries = list
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, gson.toJson(list)).apply()
+ }
+
+ /** Logs [mac]'s alert from what is known now: the live device, else its last logged match. Mutes it. */
+ suspend fun mark(context: Context, mac: String, note: String): Entry? {
+ val s = DeviceRegistry.get(mac)
+ val last = AppDatabase.getInstance(context).detectionDao().forMac(mac).firstOrNull()
+ val hit = s?.best
+ val match = when {
+ hit != null && s != null -> DetectionEntity(
+ mac = mac, label = hit.label, source = s.source.name, rssi = s.rssi, timestamp = System.currentTimeMillis(),
+ latitude = (s.bestPosition ?: s.path.lastOrNull())?.lat ?: last?.latitude,
+ longitude = (s.bestPosition ?: s.path.lastOrNull())?.lon ?: last?.longitude,
+ category = hit.category.name, confidence = hit.confidence, evidence = hit.evidence,
+ vendor = s.vendor, deviceName = s.name, radio = s.advert?.let { DeviceIntel.radioSummary(it) })
+ last != null -> last.copy(id = 0, timestamp = System.currentTimeMillis())
+ else -> return null
+ }
+ val entry = Entry(match, note.trim())
+ add(context, entry)
+ return entry
+ }
+
+ /** Puts [entry] (back) on the list and mutes its device. */
+ fun add(context: Context, entry: Entry) {
+ save(context, listOf(entry) + all(context).filter { it.match.mac != entry.match.mac })
+ AlertMutes.mute(context, entry.match.mac, AlertMutes.FOREVER)
+ }
+
+ /** Takes [mac] off the list and unmutes it. */
+ fun remove(context: Context, mac: String) {
+ save(context, all(context).filter { it.match.mac != mac })
+ AlertMutes.unmute(context, mac)
+ }
+
+ /** The rows for the list and the exports: your note first in the evidence. */
+ fun rows(context: Context): List<DetectionEntity> = all(context).map { e ->
+ if (e.note.isEmpty()) e.match else e.match.copy(evidence = "False alert: ${e.note} · ${e.match.evidence}")
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/receiver/CarAutoStart.kt b/app/src/main/java/com/rfsentinel/app/receiver/CarAutoStart.kt
index 0063890..bfeb916 100644
--- a/app/src/main/java/com/rfsentinel/app/receiver/CarAutoStart.kt
+++ b/app/src/main/java/com/rfsentinel/app/receiver/CarAutoStart.kt
@@ -89,7 +89,10 @@ class CarBluetoothReceiver : BroadcastReceiver() {
val address = device?.address ?: return
if (address !in Prefs.carDevices(context)) return
when (intent.action) {
- BluetoothDevice.ACTION_ACL_CONNECTED -> CarAutoStart.onCarConnected(context, "car Bluetooth connected")
+ BluetoothDevice.ACTION_ACL_CONNECTED -> {
+ CarAutoStart.onCarConnected(context, "car Bluetooth connected")
+ if (Prefs.carMusic(context)) Prefs.carMusicApp(context)?.let { CarMusic.play(context, it, goAsync()) }
+ }
BluetoothDevice.ACTION_ACL_DISCONNECTED -> CarAutoStart.onCarDisconnected(context, "car Bluetooth disconnected")
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/receiver/CarMusic.kt b/app/src/main/java/com/rfsentinel/app/receiver/CarMusic.kt
new file mode 100644
index 0000000..b777493
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/receiver/CarMusic.kt
@@ -0,0 +1,83 @@
+package com.rfsentinel.app.receiver
+
+import android.content.BroadcastReceiver
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.media.browse.MediaBrowser
+import android.media.session.MediaController
+import android.os.Handler
+import android.os.Looper
+import android.os.SystemClock
+import android.util.Log
+import android.view.KeyEvent
+
+/**
+ * Starts the chosen music app playing when the phone connects to the car's Bluetooth, even if the app isn't open:
+ * connects to its media service the way Android Auto does and presses Play. Apps that refuse other callers get a
+ * Play button press sent straight to them instead. Android doesn't let an app open another app's screen from the
+ * background, so nothing is opened.
+ */
+object CarMusic {
+
+ private const val TAG = "CarMusic"
+ /** The car's audio link comes up a moment after the Bluetooth connection: play then, not on the phone speaker. */
+ private const val AUDIO_DELAY_MS = 3_000L
+ private const val TIMEOUT_MS = 8_000L
+
+ /** Music apps on the phone: (package, name), sorted by name. */
+ fun apps(context: Context): List<Pair<String, String>> {
+ val pm = context.packageManager
+ val services = pm.queryIntentServices(Intent("android.media.browse.MediaBrowserService"), 0).map { it.serviceInfo.packageName }
+ val buttons = pm.queryBroadcastReceivers(Intent(Intent.ACTION_MEDIA_BUTTON), 0).map { it.activityInfo.packageName }
+ return (services + buttons).distinct().filter { it != context.packageName }
+ .map { p -> p to (runCatching { pm.getApplicationLabel(pm.getApplicationInfo(p, 0)).toString() }.getOrNull() ?: p) }
+ .sortedBy { it.second.lowercase() }
+ }
+
+ fun label(context: Context, pkg: String): String =
+ runCatching { context.packageManager.let { it.getApplicationLabel(it.getApplicationInfo(pkg, 0)).toString() } }.getOrNull() ?: pkg
+
+ /** Plays [pkg]; [pending] (from the Bluetooth broadcast) is finished once done or given up. */
+ fun play(context: Context, pkg: String, pending: BroadcastReceiver.PendingResult?) {
+ val app = context.applicationContext
+ val main = Handler(Looper.getMainLooper())
+ var browser: MediaBrowser? = null
+ var finished = false
+ fun finish(why: String) {
+ if (finished) return
+ finished = true
+ Log.i(TAG, why)
+ runCatching { browser?.disconnect() }
+ runCatching { pending?.finish() }
+ }
+ main.postDelayed({
+ val service = app.packageManager.queryIntentServices(Intent("android.media.browse.MediaBrowserService").setPackage(pkg), 0)
+ .firstOrNull()?.serviceInfo
+ if (service == null) { pressPlay(app, pkg); finish("Play pressed (no media service)"); return@postDelayed }
+ browser = MediaBrowser(app, ComponentName(service.packageName, service.name), object : MediaBrowser.ConnectionCallback() {
+ override fun onConnected() {
+ runCatching { MediaController(app, browser!!.sessionToken).transportControls.play() }
+ .onFailure { pressPlay(app, pkg) }
+ // Kept connected a moment so the app has started its playback before we let go.
+ main.postDelayed({ finish("Playing") }, 1_500)
+ }
+ override fun onConnectionFailed() { pressPlay(app, pkg); finish("Play pressed (media service refused)") }
+ override fun onConnectionSuspended() = finish("Media service stopped")
+ }, null)
+ runCatching { browser!!.connect() }.onFailure { pressPlay(app, pkg); finish("Play pressed (could not connect)") }
+ }, AUDIO_DELAY_MS)
+ main.postDelayed({ finish("Gave up waiting for the music app") }, AUDIO_DELAY_MS + TIMEOUT_MS)
+ }
+
+ /** A Play button press (down, up) sent only to [pkg]'s media button receiver: it starts the app if needed. */
+ private fun pressPlay(context: Context, pkg: String) {
+ val receiver = context.packageManager.queryBroadcastReceivers(Intent(Intent.ACTION_MEDIA_BUTTON).setPackage(pkg), 0)
+ .firstOrNull()?.activityInfo ?: return
+ val t = SystemClock.uptimeMillis()
+ for (action in listOf(KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP)) runCatching {
+ context.sendBroadcast(Intent(Intent.ACTION_MEDIA_BUTTON).setComponent(ComponentName(receiver.packageName, receiver.name))
+ .putExtra(Intent.EXTRA_KEY_EVENT, KeyEvent(t, t, action, KeyEvent.KEYCODE_MEDIA_PLAY, 0)))
+ }.onFailure { Log.w(TAG, "Play press refused", it) }
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
index f1c261c..9446b20 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -141,6 +141,34 @@ class SettingsActivity : AppCompatActivity() {
.show()
}
+ /** Lists the phone's music apps (those with a media service or Play button receiver) to start in the car. */
+ private fun chooseMusicApp() {
+ val apps = com.rfsentinel.app.receiver.CarMusic.apps(this)
+ if (apps.isEmpty()) {
+ Toast.makeText(this, "No music app found on this phone", Toast.LENGTH_LONG).show()
+ binding.carMusicSwitch.isChecked = Prefs.carMusicApp(this) != null && binding.carMusicSwitch.isChecked
+ return
+ }
+ val current = apps.indexOfFirst { it.first == Prefs.carMusicApp(this) }
+ MaterialAlertDialogBuilder(this)
+ .setTitle("Music app to play in the car")
+ .setSingleChoiceItems(apps.map { it.second }.toTypedArray(), current) { d, i ->
+ Prefs.setCarMusicApp(this, apps[i].first)
+ binding.carMusicSwitch.isChecked = true
+ if (Prefs.carDevices(this).isEmpty()) chooseCarDevices()
+ updateMusicButton()
+ d.dismiss()
+ }
+ .setNegativeButton("Cancel") { _, _ -> if (Prefs.carMusicApp(this) == null) binding.carMusicSwitch.isChecked = false }
+ .show()
+ }
+
+ private fun updateMusicButton() {
+ val app = Prefs.carMusicApp(this)
+ binding.carMusicButton.text = app?.let { "Music app: " + com.rfsentinel.app.receiver.CarMusic.label(this, it) } ?: "Choose music app"
+ binding.carMusicButton.shownIf(binding.carMusicSwitch.isChecked)
+ }
+
@android.annotation.SuppressLint("MissingPermission")
private fun updateCarDevicesText() {
val chosen = Prefs.carDevices(this)
@@ -905,6 +933,7 @@ class SettingsActivity : AppCompatActivity() {
info(binding.batteryButton, "Opens Android's battery settings: set RF Sentinel to Unrestricted so scanning keeps going with the screen off.")
info(binding.carAutoSwitch, "Starts scanning when the phone connects to your car's Bluetooth or Android Auto, and stops when you leave.")
info(binding.carRecordSwitch, "Records a GPS trace when the phone connects to your car's Bluetooth or Android Auto, and saves it when you leave. Starts scanning too if it isn't running. A trace you started yourself is never stopped.")
+ info(binding.carMusicSwitch, "When the phone connects to your car's Bluetooth, starts the music app you choose and presses Play, even if the app isn't open. Android doesn't let an app open another app's screen in the background, so its screen stays closed.")
info(binding.presetLabel, PRESETS_INFO)
info(binding.thresholdLabel, "Weak: every match, more false alarms.\n\nProbable: recommended.\n\nStrong only: the fewest alerts.\n\n" +
"Probable and Strong only don't alert on a vehicle router (Cradlepoint, Sierra Wireless) you hear day after day, " +
@@ -2375,6 +2404,14 @@ class SettingsActivity : AppCompatActivity() {
}
binding.carDevicesButton.setOnClickListener { chooseCarDevices() }
updateCarDevicesText()
+ binding.carMusicSwitch.isChecked = Prefs.carMusic(this)
+ binding.carMusicSwitch.setOnCheckedChangeListener { _, on ->
+ if (on && Prefs.carMusicApp(this) == null) chooseMusicApp()
+ else if (on && Prefs.carDevices(this).isEmpty()) chooseCarDevices()
+ updateMusicButton()
+ }
+ binding.carMusicButton.setOnClickListener { chooseMusicApp() }
+ updateMusicButton()
binding.batteryButton.setOnClickListener {
runCatching { startActivity(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)) }
.onFailure { Toast.makeText(this, "Open Android Settings > Apps > RF Sentinel > Battery", Toast.LENGTH_LONG).show() }
@@ -2763,6 +2800,7 @@ class SettingsActivity : AppCompatActivity() {
Prefs.setAutoStartOnBoot(this, binding.bootSwitch.isChecked)
Prefs.setCarAutoStart(this, binding.carAutoSwitch.isChecked)
Prefs.setCarAutoRecord(this, binding.carRecordSwitch.isChecked)
+ Prefs.setCarMusic(this, binding.carMusicSwitch.isChecked)
categorySwitches.forEach { (c, sw) -> Prefs.setCategoryEnabled(this, c, sw.isChecked) }
airTagSwitch?.let { Prefs.setExcludeAirTags(this, it.isChecked) }
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DetectionAdapter.kt b/app/src/main/java/com/rfsentinel/app/ui/DetectionAdapter.kt
index 4f2fb11..1bc4883 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DetectionAdapter.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DetectionAdapter.kt
@@ -14,7 +14,8 @@ import java.util.Date
import java.util.Locale
class DetectionAdapter(
- private val onClick: (DetectionEntity) -> Unit
+ private val onClick: (DetectionEntity) -> Unit,
+ private val onLongClick: ((DetectionEntity) -> Unit)? = null
) : RecyclerView.Adapter<DetectionAdapter.VH>() {
private var items: List<DetectionEntity> = emptyList()
@@ -65,6 +66,7 @@ class DetectionAdapter(
if (item.latitude != null) parts += String.format(Locale.US, "📍 %.4f, %.4f", item.latitude, item.longitude)
holder.binding.metaText.text = parts.joinToString(" · ")
holder.itemView.setOnClickListener { onClick(item) }
+ holder.itemView.setOnLongClickListener(onLongClick?.let { f -> android.view.View.OnLongClickListener { f(item); true } })
}
override fun getItemCount() = items.size
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.kt
index d26d860..53efdf9 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DetectionLogActivity.kt
@@ -11,6 +11,7 @@ import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.chip.Chip
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.rfsentinel.app.data.AppDatabase
+import com.rfsentinel.app.data.FalseAlerts
import com.rfsentinel.app.data.KnownDeviceDao
import com.rfsentinel.app.databinding.ActivityLogBinding
import com.rfsentinel.app.detect.Category
@@ -24,6 +25,7 @@ import java.util.Calendar
/**
* History of logged matches (the rows the exports contain). Search by address, label, maker, name or
* evidence, and narrow to today or one kind of equipment. Tap one for device details.
+ * With [EXTRA_FALSE_ALERTS]: the alerts you marked as false instead ([FalseAlerts]); long-press one to take it off.
*/
class DetectionLogActivity : AppCompatActivity() {
private lateinit var binding: ActivityLogBinding
@@ -33,16 +35,24 @@ class DetectionLogActivity : AppCompatActivity() {
private var today = false
private var category: String? = null
private var searchJob: Job? = null
+ private val falseAlerts by lazy { intent.getBooleanExtra(EXTRA_FALSE_ALERTS, false) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLogBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.root.applySystemBarInsets()
- title = "Match history"
+ title = if (falseAlerts) "False alerts" else "Match history"
supportActionBar?.setDisplayHomeAsUpEnabled(true)
- adapter = DetectionAdapter(onClick = { DeviceActions.openDetection(this, it) })
+ adapter = DetectionAdapter(onClick = { DeviceActions.openDetection(this, it) },
+ onLongClick = if (!falseAlerts) null else { d ->
+ MaterialAlertDialogBuilder(this).setTitle(d.label)
+ .setItems(arrayOf("Show details", "Remove from false alerts (alerts back on)")) { _, which ->
+ if (which == 0) DeviceActions.openDetection(this, d)
+ else DeviceActions.unmarkFalseAlert(this, d.mac) { buildChips(); search(now = true) }
+ }.show()
+ })
binding.recyclerView.layoutManager = LinearLayoutManager(this)
binding.recyclerView.adapter = adapter
binding.searchInput.doAfterTextChanged { search(now = false) }
@@ -52,7 +62,8 @@ class DetectionLogActivity : AppCompatActivity() {
/** All, Today, then one chip per kind of equipment in the log. */
private fun buildChips() = lifecycleScope.launch {
- val present = AppDatabase.getInstance(this@DetectionLogActivity).detectionDao().categories().toSet()
+ val present = if (falseAlerts) FalseAlerts.rows(this@DetectionLogActivity).map { it.category }.toSet()
+ else AppDatabase.getInstance(this@DetectionLogActivity).detectionDao().categories().toSet()
binding.filterChips.removeAllViews()
if (category != null && category !in present) category = null
fun add(label: String, checked: Boolean, pick: () -> Unit) {
@@ -76,30 +87,40 @@ class DetectionLogActivity : AppCompatActivity() {
val q = binding.searchInput.text?.toString()?.trim().orEmpty()
val since = if (today) startOfToday() else 0L
val filtered = q.isNotEmpty() || today || category != null
+ if (falseAlerts) {
+ val list = FalseAlerts.rows(this@DetectionLogActivity).filter { r ->
+ r.timestamp >= since && (category == null || r.category == category) && (q.isEmpty() ||
+ listOf(r.mac, r.label, r.vendor, r.deviceName, r.evidence).any { it?.contains(q, ignoreCase = true) == true })
+ }
+ show(list, filtered, "No false alerts logged yet. Mark one from a device's page or by long-pressing it in the list.")
+ return@launch
+ }
AppDatabase.getInstance(this@DetectionLogActivity).detectionDao()
.search(q, KnownDeviceDao.like(q), KnownDeviceDao.likeHex(q), category, since)
- .collect { list ->
- adapter.submitList(list)
- binding.emptyText.visibility = if (list.isEmpty()) View.VISIBLE else View.GONE
- binding.emptyText.text = if (filtered) "Nothing matches." else "No watchlist matches logged yet."
- val more = if (list.size >= 1000) "+" else ""
- supportActionBar?.subtitle = "${list.size}$more ${if (filtered) "found" else "logged"}"
- }
+ .collect { list -> show(list, filtered, "No watchlist matches logged yet.") }
}
}
+ private fun show(list: List<com.rfsentinel.app.data.DetectionEntity>, filtered: Boolean, empty: String) {
+ adapter.submitList(list)
+ binding.emptyText.visibility = if (list.isEmpty()) View.VISIBLE else View.GONE
+ binding.emptyText.text = if (filtered) "Nothing matches." else empty
+ val more = if (list.size >= 1000) "+" else ""
+ supportActionBar?.subtitle = "${list.size}$more ${if (filtered) "found" else "logged"}"
+ }
+
private fun startOfToday() = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 0); set(Calendar.MINUTE, 0); set(Calendar.SECOND, 0); set(Calendar.MILLISECOND, 0)
}.timeInMillis
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menu.add(0, 1, 0, "Export...")
- menu.add(0, 2, 1, "Clear match history")
+ if (!falseAlerts) menu.add(0, 2, 1, "Clear match history")
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
- 1 -> { Exporter.showExportMenu(this); true }
+ 1 -> { if (falseAlerts) Exporter.showFalseAlertExport(this) else Exporter.showExportMenu(this); true }
2 -> {
MaterialAlertDialogBuilder(this)
.setTitle("Clear match history?")
@@ -119,9 +140,11 @@ class DetectionLogActivity : AppCompatActivity() {
else -> super.onOptionsItemSelected(item)
}
- private companion object {
+ companion object {
+ const val EXTRA_FALSE_ALERTS = "false_alerts"
+
/** Short chip names for the categories. */
- fun chipLabel(c: Category) = when (c) {
+ private fun chipLabel(c: Category) = when (c) {
Category.BODY_CAM -> "Body cams"
Category.ALPR -> "Plate cameras"
Category.AUDIO_SENSOR -> "Audio sensors"
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt
index 61a93f8..f51bf74 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceActions.kt
@@ -93,6 +93,8 @@ object DeviceActions {
toast(activity, if (favorite) "Removed from favorites" else "Added to favorites")
}
}
+ if (com.rfsentinel.app.data.FalseAlerts.contains(activity, mac)) items += "Remove from false alerts" to { unmarkFalseAlert(activity, mac) }
+ else if (snap?.best != null) items += "False alert..." to { markFalseAlert(activity, mac) }
items += "I saw it: learn this device..." to { learn(activity, mac) }
if (snap?.advert != null && snap.best == null) {
items += "Report unknown device..." to { reportUnknown(activity, mac) }
@@ -109,6 +111,44 @@ object DeviceActions {
.show()
}
+ /** Logs the device's alert as false (History > False alerts) and mutes it, with an optional note. */
+ fun markFalseAlert(activity: AppCompatActivity, mac: String, done: () -> Unit = {}) {
+ val d = activity.resources.displayMetrics.density
+ val note = EditText(activity).apply { hint = "What is it really? (optional)"; setSingleLine(false) }
+ val box = LinearLayout(activity).apply {
+ orientation = LinearLayout.VERTICAL
+ val p = (20 * d).toInt()
+ setPadding(p, (8 * d).toInt(), p, 0)
+ addView(TextView(activity).apply { text = "Saved in History > False alerts to look at or export later. Its alerts are muted until you take it off that list." })
+ addView(note)
+ }
+ MaterialAlertDialogBuilder(activity)
+ .setTitle("False alert")
+ .setView(box)
+ .setPositiveButton("Save") { _, _ ->
+ activity.lifecycleScope.launch {
+ val entry = com.rfsentinel.app.data.FalseAlerts.mark(activity, mac, note.text.toString())
+ if (entry == null) { toast(activity, "Nothing flagged on this device to log"); return@launch }
+ com.rfsentinel.app.util.Undo.show(activity, "Logged as a false alert and muted") {
+ com.rfsentinel.app.data.FalseAlerts.remove(activity, mac); done()
+ }
+ done()
+ }
+ }
+ .setNegativeButton("Cancel", null)
+ .show()
+ }
+
+ /** Takes the device off the false alerts and unmutes it. */
+ fun unmarkFalseAlert(activity: AppCompatActivity, mac: String, done: () -> Unit = {}) {
+ val entry = com.rfsentinel.app.data.FalseAlerts.all(activity).firstOrNull { it.match.mac == mac } ?: return
+ com.rfsentinel.app.data.FalseAlerts.remove(activity, mac)
+ com.rfsentinel.app.util.Undo.show(activity, "Removed from false alerts, alerts back on") {
+ com.rfsentinel.app.data.FalseAlerts.add(activity, entry); done()
+ }
+ done()
+ }
+
/**
* Adds a device to the watchlist, either as this exact device (full MAC, the
* default), as its whole vendor prefix (disabled for randomized addresses), or
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
index 685d3d4..48d49ca 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceDetailActivity.kt
@@ -113,6 +113,10 @@ class DeviceDetailActivity : AppCompatActivity() {
refresh()
}
}
+ binding.actionFalseAlert.setOnClickListener {
+ if (com.rfsentinel.app.data.FalseAlerts.contains(this, mac)) DeviceActions.unmarkFalseAlert(this, mac) { refresh() }
+ else DeviceActions.markFalseAlert(this, mac) { refresh() }
+ }
binding.actionRename.setOnClickListener { rename() }
binding.actionNote.setOnClickListener { editNote() }
binding.noteText.setOnClickListener { editNote() }
@@ -267,6 +271,9 @@ class DeviceDetailActivity : AppCompatActivity() {
else -> "Whitelist"
}
binding.actionFavorite.text = if (Favorites.contains(mac)) "★ Favorite" else "☆ Favorite"
+ val falseAlert = com.rfsentinel.app.data.FalseAlerts.contains(this, mac)
+ binding.actionFalseAlert.text = if (falseAlert) "Not a false alert" else "False alert"
+ binding.actionFalseAlert.visibility = if (falseAlert || s?.best != null || pastMatches.isNotEmpty()) View.VISIBLE else View.GONE
binding.actionNote.text = if (known?.note.isNullOrBlank()) "Add note" else "Edit note"
// Sections: rebuilt only when their content changes (keeps scroll & selection stable).
diff --git a/app/src/main/java/com/rfsentinel/app/util/Exporter.kt b/app/src/main/java/com/rfsentinel/app/util/Exporter.kt
index ecb4e06..7f40484 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Exporter.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Exporter.kt
@@ -56,6 +56,20 @@ object Exporter {
/** Shortcut straight to the device history's formats (CSV / JSON): what Import history reads back. */
fun showHistoryExport(activity: AppCompatActivity) = chooseFormat(activity, Scope.HISTORY)
+ /** The false alerts you marked (History > False alerts), in the match log's formats. */
+ fun showFalseAlertExport(activity: AppCompatActivity) {
+ val formats = Scope.MATCHES.formats
+ MaterialAlertDialogBuilder(activity)
+ .setTitle("Export false alerts")
+ .setItems(formats.map { FORMAT_LABELS.getValue(it) }.toTypedArray()) { _, which ->
+ exportLog(activity, formats[which], "false_alerts", "No false alerts logged yet") {
+ com.rfsentinel.app.data.FalseAlerts.rows(activity)
+ }
+ }
+ .setNegativeButton("Cancel", null)
+ .show()
+ }
+
/** Shortcut straight to the watchlist file (it has one format). */
fun showWatchlistExport(activity: AppCompatActivity) = exportWatchlist(activity)
@@ -254,14 +268,15 @@ object Exporter {
}
}
- fun exportLog(activity: AppCompatActivity, format: String) {
+ fun exportLog(activity: AppCompatActivity, format: String, name: String = "matches", none: String = "No matches logged yet",
+ load: suspend () -> List<DetectionEntity> = { AppDatabase.getInstance(activity).detectionDao().allForExport() }) {
launchExport(activity) {
- val rows = AppDatabase.getInstance(activity).detectionDao().allForExport()
+ val rows = load()
val usable = if (format == "csv" || format == "json") rows else rows.filter { it.latitude != null && it.longitude != null }
if (usable.isEmpty()) {
toast(
activity,
- if (format == "csv" || format == "json") "No matches logged yet"
+ if (format == "csv" || format == "json") none
else "No GPS-tagged matches yet - turn on GPS tagging in Settings"
)
return@launchExport
@@ -278,7 +293,7 @@ object Exporter {
"json" -> "application/json"
else -> "text/csv"
}
- share(activity, "rf_sentinel_matches_${stamp()}.$format", text, mime, "Export match log")
+ share(activity, "rf_sentinel_${name}_${stamp()}.$format", text, mime, "Export ${name.replace('_', ' ')}")
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
index 1da2f8b..d9b0ccf 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
@@ -514,6 +514,12 @@ object Prefs {
/** Record a trace while in the car (chosen Bluetooth devices, or Android Auto). */
fun carAutoRecord(context: Context): Boolean = bool(context, "car_auto_record", false)
fun setCarAutoRecord(context: Context, value: Boolean) = setBool(context, "car_auto_record", value)
+ /** Start the chosen music app playing when the phone connects to the car's Bluetooth ([carMusicApp]). */
+ fun carMusic(context: Context): Boolean = bool(context, "car_music", false)
+ fun setCarMusic(context: Context, value: Boolean) = setBool(context, "car_music", value)
+ /** The music app's package name, or null before one is chosen. */
+ fun carMusicApp(context: Context): String? = sp(context).getString("car_music_app", null)
+ fun setCarMusicApp(context: Context, value: String?) = sp(context).edit { putString("car_music_app", value) }
/** True while the trace being recorded was started by the car (so leaving the car saves it). */
fun recordingByCar(context: Context): Boolean = bool(context, "recording_by_car", false)
fun setRecordingByCar(context: Context, value: Boolean) = setBool(context, "recording_by_car", value)
diff --git a/app/src/main/res/layout/activity_device_detail.xml b/app/src/main/res/layout/activity_device_detail.xml
index 6a2f3a2..c5ba18f 100644
--- a/app/src/main/res/layout/activity_device_detail.xml
+++ b/app/src/main/res/layout/activity_device_detail.xml
@@ -171,6 +171,12 @@
android:layout_height="wrap_content"
android:text="Add note" />
+ <com.google.android.material.chip.Chip
+ android:id="@+id/actionFalseAlert"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="False alert" />
+
<com.google.android.material.chip.Chip
android:id="@+id/actionLearn"
android:layout_width="wrap_content"
diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml
index 486e2ed..8cfd494 100644
--- a/app/src/main/res/layout/activity_settings.xml
+++ b/app/src/main/res/layout/activity_settings.xml
@@ -180,6 +180,12 @@
android:layout_height="wrap_content"
android:text="Record a trace in the car" />
+ <com.google.android.material.switchmaterial.SwitchMaterial
+ android:id="@+id/carMusicSwitch"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Play music in the car" />
+
<TextView
android:id="@+id/carDevicesText"
style="@style/SettingsLabel"
@@ -192,6 +198,13 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose your car's Bluetooth" />
+
+ <Button
+ android:id="@+id/carMusicButton"
+ style="@style/Widget.MaterialComponents.Button.TextButton"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Choose music app" />
</LinearLayout>
<!-- ================= What to detect ================= -->
diff --git a/app/src/main/res/menu/menu_main.xml b/app/src/main/res/menu/menu_main.xml
index 3cd7f39..904668e 100644
--- a/app/src/main/res/menu/menu_main.xml
+++ b/app/src/main/res/menu/menu_main.xml
@@ -26,6 +26,7 @@
<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_false_alerts" android:title="False alerts" />
<item android:id="@+id/action_traces" android:title="Recorded traces" />
<item android:id="@+id/action_snapshots" android:title="Snapshots" />
<item android:id="@+id/action_history" android:title="History map &amp; timeline" />