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.

Bluetooth: fall back to the ordinary scan when the phone's Bluetooth stops twice during the extended (long-range) scan, until Android is updated; retry an extended scan that fails to start as ordinary; noted in the crash log

CIS-C01dcce3a3f0ba
diff --git a/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt b/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt
index e0e7b73..ccf7fbb 100644
--- a/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/BleScanEngine.kt
@@ -11,6 +11,8 @@ import android.content.Context
import android.os.ParcelUuid
import android.util.Log
import com.rfsentinel.app.detect.Advert
+import com.rfsentinel.app.util.CrashLog
+import com.rfsentinel.app.util.Prefs
/**
* Passive, receive-only BLE advertisement scanner. Uses only the standard
@@ -33,6 +35,9 @@ class BleScanEngine(
/** Tracked separately: either scan can fail on its own, and both must always be stopped. */
@Volatile private var scanning = false
@Volatile private var filteredScanning = false
+ /** Scanning with the extended (long-range) settings now. */
+ @Volatile var extended = false
+ private set
/** Last result from the unfiltered scan (the filtered one alone keeps alerts going but not the list). */
@Volatile var lastUnfilteredAt = 0L
@@ -76,8 +81,9 @@ class BleScanEngine(
if (!adapter.isEnabled) return
scanner = adapter.bluetoothLeScanner ?: return
- // Extended advertising (BT5) carries Remote ID message packs on newer drones.
- val extended = runCatching { adapter.isLeExtendedAdvertisingSupported }.getOrDefault(false)
+ // Extended advertising (BT5) carries Remote ID message packs on newer drones. Not where it crashed
+ // the phone's Bluetooth before ([Prefs.bleLegacyOnly]).
+ extended = runCatching { adapter.isLeExtendedAdvertisingSupported }.getOrDefault(false) && !Prefs.bleLegacyOnly(context)
// Deliver every advert immediately (no batching). For the filtered scan, aggressive
// matching reports a device from a single, even faint, advert instead of waiting
// for several strong ones - that's what extends screen-off detection range.
@@ -90,18 +96,20 @@ class BleScanEngine(
// Extended advertising (BT5) and LE Coded (long-range) PHY where the radio supports it.
if (extended) setLegacy(false).setPhy(ScanSettings.PHY_LE_ALL_SUPPORTED)
}.build()
-
- try {
- scanner?.startScan(null, settings(scanMode), callback)
- scanning = true
+ fun begin(): Boolean = try {
+ scanner?.startScan(null, settings(scanMode), callback); true
} catch (e: SecurityException) {
// BLUETOOTH_SCAN (API 31+) or location (API <= 30) not granted.
- scanning = false
- return
- } catch (e: IllegalStateException) {
- scanning = false
- return
+ false
+ } catch (e: Exception) {
+ // Adapter turning off (IllegalStateException), or a Bluetooth stack that rejects the extended settings.
+ Log.w(TAG, "BLE scan failed to start (extended: $extended)", e); false
}
+
+ scanning = begin()
+ if (!scanning && extended) { extended = false; scanning = begin() }
+ if (!scanning) return
+ Prefs.setBleExtendedRunning(context, extended)
try {
// Same intensity as the main scan: this is the only scan Android keeps running with
// the screen off, so a lower duty cycle here is where passing devices get missed.
@@ -119,6 +127,7 @@ class BleScanEngine(
// Adapter already turned off (IllegalStateException) or permission revoked.
}
}
+ if (extended) { extended = false; Prefs.setBleExtendedRunning(context, false) }
if (filteredScanning) {
try { scanner?.stopScan(filteredCallback) } catch (e: Exception) {}
}
@@ -165,5 +174,13 @@ class BleScanEngine(
companion object {
private const val TAG = "BleScanEngine"
+
+ /** The phone's Bluetooth stopped during an extended scan ([why]): the second time on this Android build, ordinary scans only. */
+ fun strike(context: Context, why: String) {
+ val n = Prefs.addBleExtendedStrike(context)
+ Log.w(TAG, "Extended scan strike $n: $why")
+ if (n == 2) CrashLog.note(context, "Bluetooth: $why during the extended (long-range) scan, twice. The phone's " +
+ "Bluetooth may not handle it: using the ordinary scan until Android is updated.")
+ }
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
index 13d66e2..f18d849 100644
--- a/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
+++ b/app/src/main/java/com/rfsentinel/app/service/ScanForegroundService.kt
@@ -103,6 +103,8 @@ class ScanForegroundService : Service() {
/** Android downgrades an unfiltered BLE scan to opportunistic after ~30 min; restart before. */
private const val BLE_RESTART_INTERVAL_MS = 25 * 60 * 1000L
+ /** Bluetooth back on this soon after it went off: Android restarting it after a crash, not you turning it off. */
+ private const val BT_RESTART_MS = 15_000L
/** Watchdog: a scanner silent this long is restarted. */
private const val BLE_SILENCE_MS = 2 * 60_000L
/** After the screen comes on, the unfiltered BLE scan should be delivering again within this long. */
@@ -312,12 +314,23 @@ class ScanForegroundService : Service() {
private val alprLastDistance = HashMap<String, Double>()
private val alprLastAlert = HashMap<String, Long>()
+ /** When Bluetooth went off during an extended scan; 0 when it didn't. */
+ private var btDroppedAt = 0L
+
/** Starts BLE scanning if the user turns Bluetooth on after the service started. */
private val btStateReceiver = object : BroadcastReceiver() {
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 -> stopBle() // its periodic restart too
+ BluetoothAdapter.STATE_ON -> {
+ // Off and straight back on during an extended scan: Android restarting its crashed Bluetooth.
+ if (System.currentTimeMillis() - btDroppedAt < BT_RESTART_MS) BleScanEngine.strike(context, "Bluetooth restarted")
+ btDroppedAt = 0L
+ if (Prefs.bleEnabled(context)) startBle()
+ }
+ BluetoothAdapter.STATE_TURNING_OFF, BluetoothAdapter.STATE_OFF -> {
+ if (bleEngine.extended) btDroppedAt = System.currentTimeMillis()
+ stopBle() // its periodic restart too
+ }
}
}
}
diff --git a/app/src/main/java/com/rfsentinel/app/util/CrashLog.kt b/app/src/main/java/com/rfsentinel/app/util/CrashLog.kt
index 6820b31..8cba806 100644
--- a/app/src/main/java/com/rfsentinel/app/util/CrashLog.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/CrashLog.kt
@@ -50,12 +50,16 @@ object CrashLog {
append(context, entry)
}
- private fun append(context: Context, entry: String) {
+ /** A line for the developer, without the "closed unexpectedly" prompt. */
+ fun note(context: Context, text: String) =
+ append(context, "==== ${SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.US).format(Date())} ====\n$text\n\n", prompt = false)
+
+ private fun append(context: Context, entry: String, prompt: Boolean = true) = synchronized(this) {
val f = file(context)
val old = if (f.exists()) f.readText() else ""
f.writeText((old + entry).takeLast(MAX_BYTES))
// commit(): the process is about to die.
- context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean("unseen", true).commit()
+ if (prompt) context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean("unseen", true).commit()
}
/**
@@ -75,6 +79,9 @@ object CrashLog {
val noted = exits.filter { it.timestamp > since && noteworthy(it.reason, it.importance) }.sortedBy { it.timestamp }
prefs.edit().putLong("exits_seen", maxOf(newest, seen)).apply()
if (noted.isNotEmpty()) append(context, noted.joinToString("") { exitEntry(it) })
+ // Killed along with the phone's Bluetooth during an extended scan: counts against that scan.
+ if (Prefs.bleExtendedRunning(context) && noted.any { it.reason == ApplicationExitInfo.REASON_DEPENDENCY_DIED })
+ com.rfsentinel.app.service.BleScanEngine.strike(context, "the app was killed with a service it used")
}
/** Worth logging: not a normal end (closed, force-stopped, updated) nor a crash [install] already logged. */
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 39ae914..15e378c 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
@@ -33,6 +33,17 @@ object Prefs {
/** ScanSettings.SCAN_MODE_*; low latency catches the most but costs the most battery. */
fun bleScanMode(context: Context): Int = int(context, "ble_scan_mode", ScanSettings.SCAN_MODE_LOW_LATENCY)
+ /** Times the phone's Bluetooth stopped during an extended (long-range) scan on this Android build. */
+ fun bleExtendedStrikes(context: Context, build: String = android.os.Build.FINGERPRINT): Int =
+ if (sp(context).getString("ble_ext_build", null) == build) int(context, "ble_ext_strikes", 0) else 0
+ /** One more of [bleExtendedStrikes]; returns how many now. */
+ fun addBleExtendedStrike(context: Context, build: String = android.os.Build.FINGERPRINT): Int =
+ (bleExtendedStrikes(context, build) + 1).also { n -> sp(context).edit { putString("ble_ext_build", build); putInt("ble_ext_strikes", n) } }
+ /** Its Bluetooth stopped twice during extended scans: ordinary scans only, until Android is updated. */
+ fun bleLegacyOnly(context: Context, build: String = android.os.Build.FINGERPRINT) = bleExtendedStrikes(context, build) >= 2
+ /** An extended scan is running; still set at the next start when the app was killed during one. */
+ fun bleExtendedRunning(context: Context): Boolean = bool(context, "ble_ext_running", false)
+ fun setBleExtendedRunning(context: Context, v: Boolean) = setBool(context, "ble_ext_running", v)
fun setBleScanMode(context: Context, value: Int) = setInt(context, "ble_scan_mode", value)
fun autoStartOnBoot(context: Context): Boolean = bool(context, "auto_start_boot", false)
diff --git a/app/src/test/java/com/rfsentinel/app/util/BleFallbackTest.kt b/app/src/test/java/com/rfsentinel/app/util/BleFallbackTest.kt
new file mode 100644
index 0000000..f2bbe73
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/util/BleFallbackTest.kt
@@ -0,0 +1,41 @@
+package com.rfsentinel.app.util
+
+import android.app.Application
+import android.content.Context
+import androidx.test.core.app.ApplicationProvider
+import com.rfsentinel.app.service.BleScanEngine
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+
+/** The extended Bluetooth scan falls back to the ordinary one after the phone's Bluetooth stops twice, until Android updates. */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35], application = Application::class)
+class BleFallbackTest {
+ private val ctx: Context = ApplicationProvider.getApplicationContext()
+
+ @Test
+ fun twiceOnOneBuildThenFreshAfterAnUpdate() {
+ assertFalse(Prefs.bleLegacyOnly(ctx, "build-a"))
+ assertEquals(1, Prefs.addBleExtendedStrike(ctx, "build-a"))
+ assertFalse(Prefs.bleLegacyOnly(ctx, "build-a"))
+ assertEquals(2, Prefs.addBleExtendedStrike(ctx, "build-a"))
+ assertTrue(Prefs.bleLegacyOnly(ctx, "build-a"))
+ // Android updated: the extended scan gets another chance.
+ assertFalse(Prefs.bleLegacyOnly(ctx, "build-b"))
+ assertEquals(1, Prefs.addBleExtendedStrike(ctx, "build-b"))
+ }
+
+ @Test
+ fun secondStrikeIsNotedInTheCrashLogWithoutThePrompt() {
+ BleScanEngine.strike(ctx, "Bluetooth restarted")
+ assertFalse(CrashLog.hasCrashes(ctx))
+ BleScanEngine.strike(ctx, "Bluetooth restarted")
+ assertTrue(CrashLog.file(ctx).readText().contains("using the ordinary scan"))
+ assertFalse(ctx.getSharedPreferences("crash_log", Context.MODE_PRIVATE).getBoolean("unseen", false))
+ }
+}