Skip to content

Colota - Android GPS Location tracker

refactor: move Bluetooth tracking out of ConditionMonitor and the export folder out of AutoExportWorker (#997)

Max Dietrichd56d4e5ba007
diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.md
index ffcf715f..03e2a683 100644
--- a/apps/docs/docs/development/architecture.md
+++ b/apps/docs/docs/development/architecture.md
@@ -269,7 +269,7 @@ Database access layer for tracking profiles and trip events. Maintains a `TimedC
### ConditionMonitor
-Monitors charging state via `BroadcastReceiver`, Android Auto connection via the `CarConnection` API, Bluetooth device connections via the ACL `BroadcastReceiver` (seeded from the A2DP and headset profile proxies on every monitor start, since ACL broadcasts report changes only; a device on neither profile is seen at its next connect), and Wi-Fi transport changes from `NetworkMonitor`, reading the network name one-shot when a named-network profile needs it: on every Wi-Fi network that comes or goes and when Location comes back on, because a name read while Location was off is blank. Forwards state changes to `ProfileManager` for condition evaluation.
+Monitors charging state via `BroadcastReceiver`, Android Auto connection via the `CarConnection` API, Bluetooth device connections through `BluetoothDeviceMonitor`, an ACL `BroadcastReceiver` (seeded from the A2DP and headset profile proxies on every monitor start, since ACL broadcasts report changes only; a device on neither profile is seen at its next connect), and Wi-Fi transport changes from `NetworkMonitor`, reading the network name one-shot when a named-network profile needs it: on every Wi-Fi network that comes or goes and when Location comes back on, because a name read while Location was off is blank. Forwards state changes to `ProfileManager` for condition evaluation.
### ProfileConstants
@@ -301,7 +301,7 @@ For backups, two `internal` methods support the export/import flow without expos
| `TimedCache` | Generic TTL cache used for queue count, device info, profiles, and network state |
| `BuildConfigModule` | Exposes the version name, version code, flavor and device language to JS, plus `getSystemPalette` - the Android 12+ wallpaper tonal steps as `#RRGGBB` hex, null below API 31 - and the in-app language through AppCompat's per-app locale API: `getAppLanguage` (the pick and the language in use) and `setAppLanguage`. `MainActivity` handles `locale` and `layoutDirection` itself, so a switch does not recreate it, and native text is read through `util/AppLanguage`, because below Android 13 AppCompat localises activities only |
| `AppLogger` | Centralized logger - always active, all tags prefixed with `Colota.` for logcat filtering |
-| `AutoExportWorker` | WorkManager `CoroutineWorker` enqueued by `AutoExportAlarmReceiver` - performs the export (chunked writes to a per-run temp file, foreground service, retries, retention cleanup), verifies the copy by bytes written and re-arms the next alarm in `finally` |
+| `AutoExportWorker` | WorkManager `CoroutineWorker` enqueued by `AutoExportAlarmReceiver` - performs the export (chunked writes to a per-run temp file, foreground service, retries) and re-arms the next alarm in `finally`. `ExportFolder` copies the file into the chosen folder, verified by bytes written, and runs the retention cleanup |
| `AutoExportAlarmReceiver` | Broadcast receiver fired by AlarmManager at the configured time - hands off to `AutoExportWorker` because the receiver's 10s budget can't run an export |
| `AutoExportScheduler` | Arms `AlarmManager.setAndAllowWhileIdle` for the next configured wall-clock time. Called on enable, by the alarm receiver on every fire, after each worker run, after schedule edits and on boot |
| `AutoExportConfig` | Typed data class wrapping auto-export settings (interval, time-of-day, weekday, day-of-month, enabledAt) from the SQLite settings table with validation, `isExportDue()` and `nextExportTimestamp()` |
diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt
index ac590916..928a6016 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt
@@ -16,7 +16,6 @@ import android.net.Uri
import android.os.Build
import android.provider.DocumentsContract
import androidx.core.app.NotificationCompat
-import androidx.documentfile.provider.DocumentFile
import androidx.work.CoroutineWorker
import androidx.work.ForegroundInfo
import androidx.work.WorkerParameters
@@ -40,9 +39,6 @@ class AutoExportWorker(
params: WorkerParameters
) : CoroutineWorker(appContext, params) {
- // Only the SAF copy raises this, so a directory verdict can never be reached from a database read
- private class DirectoryAccessException(message: String) : Exception(message)
-
companion object {
private const val TAG = "AutoExportWorker"
private const val CHANNEL_ID = "auto_export"
@@ -131,6 +127,7 @@ class AutoExportWorker(
val ext = ExportConverters.extensionFor(config.format)
val dirUri = Uri.parse(config.uri)
+ val folder = ExportFolder(appContext, dirUri)
// Used for the incremental upper bound, the saved lastExport and the filename stamp, so
// points written mid-export aren't dropped and the name matches the range it covers.
@@ -167,18 +164,18 @@ class AutoExportWorker(
tempFile.delete()
AppLogger.i(TAG, "No locations to export")
showNotification(strings.getString(R.string.auto_export_title), strings.getString(R.string.auto_export_nothing_new))
- cleanupOldExports(dirUri, config)
+ folder.cleanup(config)
if (isManualRun) LocationServiceModule.sendAutoExportEvent(true, null, 0, null)
return Result.success()
}
- val destDocFile = copyToSafDirectory(dirUri, fileName, tempFile, config.format)
+ val destDocFile = folder.copyIn(fileName, tempFile, config.format)
tempFile.delete()
config.saveLastExportTimestamp(db, exportStartSec)
- cleanupOldExports(dirUri, config)
+ folder.cleanup(config)
// SAF renames on collision (foo.gpx -> "foo (1).gpx"), so report what it created.
val savedName = destDocFile.name ?: fileName
@@ -214,7 +211,7 @@ class AutoExportWorker(
userMessage = strings.getString(R.string.auto_export_invalid_config, e.message.orEmpty()),
retry = false
)
- } catch (e: DirectoryAccessException) {
+ } catch (e: ExportFolder.DirectoryAccessException) {
handleExportFailure(
tempFile, config, db, e,
error = "Directory access failed: ${e.message}",
@@ -267,90 +264,6 @@ class AutoExportWorker(
return if (retry) Result.retry() else Result.failure()
}
- private fun copyToSafDirectory(
- dirUri: Uri,
- fileName: String,
- sourceFile: File,
- format: String
- ): DocumentFile {
- val resolver = appContext.contentResolver
- val mimeType = ExportConverters.mimeTypeFor(format)
-
- val docFile = DocumentFile.fromTreeUri(appContext, dirUri)
- ?.createFile(mimeType, fileName)
- ?: throw DirectoryAccessException("Failed to create file in selected directory")
-
- val expected = sourceFile.length()
- try {
- val copied = resolver.openOutputStream(docFile.uri)?.use { outStream ->
- sourceFile.inputStream().use { inStream ->
- inStream.copyTo(outStream)
- }
- } ?: throw DirectoryAccessException("Failed to open output stream")
- // Verified by what was written, never by querying the document back: cloud providers report size 0 until synced
- if (copied != expected) {
- throw IOException("Export verification failed: copied $copied of $expected bytes")
- }
- } catch (e: Exception) {
- docFile.delete()
- throw e
- }
- return docFile
- }
-
- /**
- * Deletes only files the configured template could have produced, so subfolders and sync
- * artifacts are left alone. Selection lives in [ExportFilenames.selectForDeletion] so it is
- * testable without SAF.
- */
- private fun cleanupOldExports(dirUri: Uri, config: AutoExportConfig) {
- if (config.retentionCount <= 0) {
- AppLogger.d(TAG, "Export cleanup skipped - retention is unlimited")
- return
- }
-
- try {
- val dir = DocumentFile.fromTreeUri(appContext, dirUri) ?: return
- val matchers = ExportFilenames.exportFileMatchers(config.filenameTemplate, Build.MODEL)
-
- // Each DocumentFile getter is its own query, so only the names that already match pay
- // for lastModified and isFile. A shared folder can hold far more files than ours.
- val listed = dir.listFiles()
- val candidates = listed
- .map { it to it.name.orEmpty() }
- .filter { (_, name) -> matchers.any { it.matches(name) } }
- .map { (file, name) ->
- file to ExportFilenames.ExportEntry(name, file.lastModified(), file.isFile)
- }
- val selected = ExportFilenames
- .selectForDeletion(candidates.map { it.second }, config.retentionCount, matchers)
- .map { it.name }
- val doomed = selected.toMutableList()
-
- var deleted = 0
- candidates.forEach { (file, entry) ->
- // Re-checked here because the match is by display name: a directory sharing a name
- // with a selected file would otherwise be deleted, recursively.
- // remove() rather than contains() so duplicate display names delete one apiece.
- if (entry.isFile && doomed.remove(entry.name)) {
- file.delete()
- deleted++
- AppLogger.d(TAG, "Cleaned up old export: ${entry.name}")
- }
- }
-
- // Logged on every run, zeros included: a cleanup that recognised none of its own files
- // is otherwise indistinguishable from one that found nothing to delete.
- AppLogger.i(
- TAG,
- "Export cleanup: ${listed.size} in folder, ${candidates.size} matched, " +
- "${selected.size} selected, $deleted deleted (keeping ${config.retentionCount})"
- )
- } catch (e: Exception) {
- AppLogger.w(TAG, "Export cleanup failed (non-critical): ${e.message}")
- }
- }
-
private fun ensureNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val nm = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/ExportFolder.kt b/apps/mobile/android/app/src/main/java/com/colota/export/ExportFolder.kt
new file mode 100644
index 00000000..b17c14c7
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/export/ExportFolder.kt
@@ -0,0 +1,108 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.export
+
+import android.content.Context
+import android.net.Uri
+import android.os.Build
+import androidx.documentfile.provider.DocumentFile
+import com.Colota.util.AppLogger
+import java.io.File
+import java.io.IOException
+
+/** The folder auto-export writes into: copies a finished export in and keeps only the newest of its own files. */
+class ExportFolder(private val context: Context, private val dirUri: Uri) {
+
+ // Only the copy raises this, so a directory verdict can never be reached from a database read
+ class DirectoryAccessException(message: String) : Exception(message)
+
+ companion object {
+ private const val TAG = "AutoExportWorker"
+ }
+
+ fun copyIn(
+ fileName: String,
+ sourceFile: File,
+ format: String
+ ): DocumentFile {
+ val resolver = context.contentResolver
+ val mimeType = ExportConverters.mimeTypeFor(format)
+
+ val docFile = DocumentFile.fromTreeUri(context, dirUri)
+ ?.createFile(mimeType, fileName)
+ ?: throw DirectoryAccessException("Failed to create file in selected directory")
+
+ val expected = sourceFile.length()
+ try {
+ val copied = resolver.openOutputStream(docFile.uri)?.use { outStream ->
+ sourceFile.inputStream().use { inStream ->
+ inStream.copyTo(outStream)
+ }
+ } ?: throw DirectoryAccessException("Failed to open output stream")
+ // Verified by what was written, never by querying the document back: cloud providers report size 0 until synced
+ if (copied != expected) {
+ throw IOException("Export verification failed: copied $copied of $expected bytes")
+ }
+ } catch (e: Exception) {
+ docFile.delete()
+ throw e
+ }
+ return docFile
+ }
+
+ /**
+ * Deletes only files the configured template could have produced, so subfolders and sync
+ * artifacts are left alone. Selection lives in [ExportFilenames.selectForDeletion] so it is
+ * testable without SAF.
+ */
+ fun cleanup(config: AutoExportConfig) {
+ if (config.retentionCount <= 0) {
+ AppLogger.d(TAG, "Export cleanup skipped - retention is unlimited")
+ return
+ }
+
+ try {
+ val dir = DocumentFile.fromTreeUri(context, dirUri) ?: return
+ val matchers = ExportFilenames.exportFileMatchers(config.filenameTemplate, Build.MODEL)
+
+ // Each DocumentFile getter is its own query, so only the names that already match pay
+ // for lastModified and isFile. A shared folder can hold far more files than ours.
+ val listed = dir.listFiles()
+ val candidates = listed
+ .map { it to it.name.orEmpty() }
+ .filter { (_, name) -> matchers.any { it.matches(name) } }
+ .map { (file, name) ->
+ file to ExportFilenames.ExportEntry(name, file.lastModified(), file.isFile)
+ }
+ val selected = ExportFilenames
+ .selectForDeletion(candidates.map { it.second }, config.retentionCount, matchers)
+ .map { it.name }
+ val doomed = selected.toMutableList()
+
+ var deleted = 0
+ candidates.forEach { (file, entry) ->
+ // Re-checked here because the match is by display name: a directory sharing a name
+ // with a selected file would otherwise be deleted, recursively.
+ // remove() rather than contains() so duplicate display names delete one apiece.
+ if (entry.isFile && doomed.remove(entry.name)) {
+ file.delete()
+ deleted++
+ AppLogger.d(TAG, "Cleaned up old export: ${entry.name}")
+ }
+ }
+
+ // Logged on every run, zeros included: a cleanup that recognised none of its own files
+ // is otherwise indistinguishable from one that found nothing to delete.
+ AppLogger.i(
+ TAG,
+ "Export cleanup: ${listed.size} in folder, ${candidates.size} matched, " +
+ "${selected.size} selected, $deleted deleted (keeping ${config.retentionCount})"
+ )
+ } catch (e: Exception) {
+ AppLogger.w(TAG, "Export cleanup failed (non-critical): ${e.message}")
+ }
+ }
+}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/BluetoothDeviceMonitor.kt b/apps/mobile/android/app/src/main/java/com/colota/service/BluetoothDeviceMonitor.kt
new file mode 100644
index 00000000..e980c844
--- /dev/null
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/BluetoothDeviceMonitor.kt
@@ -0,0 +1,172 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota.service
+
+import android.Manifest
+import android.annotation.SuppressLint
+import android.bluetooth.BluetoothAdapter
+import android.bluetooth.BluetoothDevice
+import android.bluetooth.BluetoothManager
+import android.bluetooth.BluetoothProfile
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
+import android.content.pm.PackageManager
+import android.os.Build
+import com.Colota.util.AppLogger
+
+/** Tracks the connected Bluetooth devices by their ACL broadcasts and hands on the whole set at every change. */
+class BluetoothDeviceMonitor(
+ private val context: Context,
+ private val onDevicesChanged: (Set<String>) -> Unit
+) {
+ companion object {
+ private const val TAG = "ConditionMonitor"
+ }
+
+ private var receiver: BroadcastReceiver? = null
+ // Main thread only: the receiver and the profile proxy callbacks both land there.
+ private val connectedAddresses = mutableSetOf<String>()
+ private var generation = 0
+
+ /**
+ * ACL broadcasts carry changes only, so the devices already connected when tracking starts are
+ * read once from the A2DP and headset proxies, the two profiles a car head unit connects with.
+ * The generation drops proxy results that arrive after stop().
+ */
+ fun start() {
+ connectedAddresses.clear()
+ if (!hasBluetoothPermission()) {
+ AppLogger.w(TAG, "Bluetooth condition needs the Nearby devices permission")
+ onDevicesChanged(emptySet())
+ return
+ }
+ val adapter = bluetoothAdapter()
+ if (adapter == null) {
+ AppLogger.w(TAG, "Bluetooth unavailable on this device")
+ onDevicesChanged(emptySet())
+ return
+ }
+
+ registerReceiver()
+ seedConnectedDevices(adapter)
+ }
+
+ fun stop() {
+ receiver?.let {
+ try { context.unregisterReceiver(it) } catch (_: Exception) {}
+ }
+ receiver = null
+ generation++
+ }
+
+ private fun registerReceiver() {
+ receiver = object : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ when (intent.action) {
+ BluetoothDevice.ACTION_ACL_CONNECTED -> {
+ val address = deviceAddressOf(intent) ?: return
+ AppLogger.d(TAG, "Bluetooth device connected")
+ connectedAddresses.add(address)
+ push()
+ }
+ BluetoothDevice.ACTION_ACL_DISCONNECTED -> {
+ val address = deviceAddressOf(intent) ?: return
+ AppLogger.d(TAG, "Bluetooth device disconnected")
+ connectedAddresses.remove(address)
+ push()
+ }
+ BluetoothAdapter.ACTION_STATE_CHANGED -> {
+ val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
+ if (state == BluetoothAdapter.STATE_TURNING_OFF || state == BluetoothAdapter.STATE_OFF) {
+ AppLogger.d(TAG, "Bluetooth turned off")
+ connectedAddresses.clear()
+ push()
+ }
+ }
+ }
+ }
+ }
+
+ val filter = IntentFilter().apply {
+ addAction(BluetoothDevice.ACTION_ACL_CONNECTED)
+ addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
+ addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
+ }
+ // Exported on purpose: the Bluetooth module sends these as its own uid, not as system, so a
+ // not-exported receiver never gets them. They are protected broadcasts no other app can send.
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ context.registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED)
+ } else {
+ context.registerReceiver(receiver, filter)
+ }
+ }
+
+ @SuppressLint("MissingPermission")
+ private fun seedConnectedDevices(adapter: BluetoothAdapter) {
+ if (!adapter.isEnabled) {
+ push()
+ return
+ }
+
+ val seedGeneration = generation
+ val profiles = listOf(BluetoothProfile.A2DP, BluetoothProfile.HEADSET)
+ var pending = profiles.size
+ fun settle() {
+ if (--pending == 0 && seedGeneration == generation) push()
+ }
+
+ val listener = object : BluetoothProfile.ServiceListener {
+ @SuppressLint("MissingPermission")
+ override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
+ try {
+ if (seedGeneration == generation) {
+ proxy.connectedDevices.forEach { connectedAddresses.add(it.address.uppercase()) }
+ }
+ } catch (e: SecurityException) {
+ AppLogger.w(TAG, "Reading connected Bluetooth devices denied: ${e.message}")
+ } finally {
+ try { adapter.closeProfileProxy(profile, proxy) } catch (_: Exception) {}
+ }
+ settle()
+ }
+
+ override fun onServiceDisconnected(profile: Int) {}
+ }
+
+ profiles.forEach { profile ->
+ val requested = try {
+ adapter.getProfileProxy(context, listener, profile)
+ } catch (e: Exception) {
+ AppLogger.w(TAG, "Bluetooth profile $profile proxy unavailable: ${e.message}")
+ false
+ }
+ if (!requested) settle()
+ }
+ }
+
+ private fun push() {
+ onDevicesChanged(connectedAddresses.toSet())
+ }
+
+ private fun deviceAddressOf(intent: Intent): String? {
+ val device = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java)
+ } else {
+ @Suppress("DEPRECATION")
+ intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
+ }
+ return device?.address?.uppercase()
+ }
+
+ private fun bluetoothAdapter(): BluetoothAdapter? =
+ (context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter
+
+ private fun hasBluetoothPermission(): Boolean =
+ Build.VERSION.SDK_INT < Build.VERSION_CODES.S ||
+ context.checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
+}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ConditionMonitor.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ConditionMonitor.kt
index 15511ef6..8c91bcdd 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/ConditionMonitor.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ConditionMonitor.kt
@@ -5,13 +5,6 @@
package com.Colota.service
-import android.Manifest
-import android.annotation.SuppressLint
-import android.bluetooth.BluetoothAdapter
-import android.bluetooth.BluetoothDevice
-import android.bluetooth.BluetoothManager
-import android.bluetooth.BluetoothProfile
-import android.content.pm.PackageManager
import android.os.Build
import android.content.BroadcastReceiver
import android.content.Context
@@ -34,7 +27,7 @@ import com.Colota.util.AppLogger
* from the service's [NetworkMonitor], which tracks connected Wi-Fi networks
* with a plain (unflagged) callback; a named-network profile reads the name
* through a one-shot location-flagged probe when that transport changes.
- * Bluetooth devices are tracked by their ACL connection broadcasts.
+ * Bluetooth devices come from [BluetoothDeviceMonitor].
*
* All observers are registered programmatically so they only run while
* the foreground service is active.
@@ -55,10 +48,7 @@ class ConditionMonitor(
// Main thread only: invalidates in-flight SSID probes when a newer network change arrives.
private var wifiPushGeneration = 0
private var wifiMonitorActive = false
- private var bluetoothReceiver: BroadcastReceiver? = null
- // Main thread only: the receiver and the profile proxy callbacks both land there.
- private val connectedBluetoothAddresses = mutableSetOf<String>()
- private var bluetoothGeneration = 0
+ private val bluetoothMonitor = BluetoothDeviceMonitor(context) { profileManager.onBluetoothDevicesChanged(it) }
fun start() {
// Unregister first to prevent duplicate observers on repeated start() calls
@@ -81,7 +71,7 @@ class ConditionMonitor(
}
if (ProfileConstants.CONDITION_BLUETOOTH_DEVICE in needed) {
- startBluetoothMonitor()
+ bluetoothMonitor.start()
}
AppLogger.d(TAG, "Condition monitors started for: ${needed.ifEmpty { setOf("none") }}")
@@ -92,8 +82,7 @@ class ConditionMonitor(
stopCarConnectionMonitor()
networkMonitor.setWifiStateListener(null)
wifiMonitorActive = false
- bluetoothReceiver = unregisterSafely(bluetoothReceiver)
- bluetoothGeneration++
+ bluetoothMonitor.stop()
AppLogger.d(TAG, "Condition monitors stopped")
}
@@ -204,135 +193,6 @@ class ConditionMonitor(
}
}
- /**
- * ACL broadcasts carry changes only, so the devices already connected when tracking starts are
- * read once from the A2DP and headset proxies, the two profiles a car head unit connects with.
- * The generation drops proxy results that arrive after stop().
- */
- private fun startBluetoothMonitor() {
- connectedBluetoothAddresses.clear()
- if (!hasBluetoothPermission()) {
- AppLogger.w(TAG, "Bluetooth condition needs the Nearby devices permission")
- profileManager.onBluetoothDevicesChanged(emptySet())
- return
- }
- val adapter = bluetoothAdapter()
- if (adapter == null) {
- AppLogger.w(TAG, "Bluetooth unavailable on this device")
- profileManager.onBluetoothDevicesChanged(emptySet())
- return
- }
-
- registerBluetoothReceiver()
- seedConnectedBluetoothDevices(adapter)
- }
-
- private fun registerBluetoothReceiver() {
- bluetoothReceiver = object : BroadcastReceiver() {
- override fun onReceive(context: Context, intent: Intent) {
- when (intent.action) {
- BluetoothDevice.ACTION_ACL_CONNECTED -> {
- val address = deviceAddressOf(intent) ?: return
- AppLogger.d(TAG, "Bluetooth device connected")
- connectedBluetoothAddresses.add(address)
- pushBluetoothState()
- }
- BluetoothDevice.ACTION_ACL_DISCONNECTED -> {
- val address = deviceAddressOf(intent) ?: return
- AppLogger.d(TAG, "Bluetooth device disconnected")
- connectedBluetoothAddresses.remove(address)
- pushBluetoothState()
- }
- BluetoothAdapter.ACTION_STATE_CHANGED -> {
- val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
- if (state == BluetoothAdapter.STATE_TURNING_OFF || state == BluetoothAdapter.STATE_OFF) {
- AppLogger.d(TAG, "Bluetooth turned off")
- connectedBluetoothAddresses.clear()
- pushBluetoothState()
- }
- }
- }
- }
- }
-
- val filter = IntentFilter().apply {
- addAction(BluetoothDevice.ACTION_ACL_CONNECTED)
- addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
- addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
- }
- // Exported on purpose: the Bluetooth module sends these as its own uid, not as system, so a
- // not-exported receiver never gets them. They are protected broadcasts no other app can send.
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
- context.registerReceiver(bluetoothReceiver, filter, Context.RECEIVER_EXPORTED)
- } else {
- context.registerReceiver(bluetoothReceiver, filter)
- }
- }
-
- @SuppressLint("MissingPermission")
- private fun seedConnectedBluetoothDevices(adapter: BluetoothAdapter) {
- if (!adapter.isEnabled) {
- pushBluetoothState()
- return
- }
-
- val generation = bluetoothGeneration
- val profiles = listOf(BluetoothProfile.A2DP, BluetoothProfile.HEADSET)
- var pending = profiles.size
- fun settle() {
- if (--pending == 0 && generation == bluetoothGeneration) pushBluetoothState()
- }
-
- val listener = object : BluetoothProfile.ServiceListener {
- @SuppressLint("MissingPermission")
- override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
- try {
- if (generation == bluetoothGeneration) {
- proxy.connectedDevices.forEach { connectedBluetoothAddresses.add(it.address.uppercase()) }
- }
- } catch (e: SecurityException) {
- AppLogger.w(TAG, "Reading connected Bluetooth devices denied: ${e.message}")
- } finally {
- try { adapter.closeProfileProxy(profile, proxy) } catch (_: Exception) {}
- }
- settle()
- }
-
- override fun onServiceDisconnected(profile: Int) {}
- }
-
- profiles.forEach { profile ->
- val requested = try {
- adapter.getProfileProxy(context, listener, profile)
- } catch (e: Exception) {
- AppLogger.w(TAG, "Bluetooth profile $profile proxy unavailable: ${e.message}")
- false
- }
- if (!requested) settle()
- }
- }
-
- private fun pushBluetoothState() {
- profileManager.onBluetoothDevicesChanged(connectedBluetoothAddresses.toSet())
- }
-
- private fun deviceAddressOf(intent: Intent): String? {
- val device = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
- intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java)
- } else {
- @Suppress("DEPRECATION")
- intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
- }
- return device?.address?.uppercase()
- }
-
- private fun bluetoothAdapter(): BluetoothAdapter? =
- (context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter
-
- private fun hasBluetoothPermission(): Boolean =
- Build.VERSION.SDK_INT < Build.VERSION_CODES.S ||
- context.checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
-
private fun readCurrentChargingState(): Boolean {
val batteryIntent = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
val status = batteryIntent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/export/ExportFolderTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/export/ExportFolderTest.kt
new file mode 100644
index 00000000..87976a7e
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/export/ExportFolderTest.kt
@@ -0,0 +1,85 @@
+package com.Colota.export
+
+import android.content.Context
+import android.net.Uri
+import androidx.documentfile.provider.DocumentFile
+import com.Colota.util.AppLogger
+import io.mockk.*
+import org.junit.After
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+
+/** Robolectric for `Build.MODEL`, which the stubbed android.jar leaves null and the matchers read. */
+@RunWith(RobolectricTestRunner::class)
+class ExportFolderTest {
+
+ private val context = mockk<Context>(relaxed = true)
+ private val dirUri = mockk<Uri>()
+ private val tree = mockk<DocumentFile>()
+
+ @Before
+ fun setUp() {
+ mockkStatic(DocumentFile::class)
+ every { DocumentFile.fromTreeUri(any(), any()) } returns tree
+ mockkObject(AppLogger)
+ every { AppLogger.d(any(), any()) } just Runs
+ every { AppLogger.i(any(), any()) } just Runs
+ every { AppLogger.w(any(), any()) } just Runs
+ }
+
+ @After
+ fun tearDown() {
+ unmockkStatic(DocumentFile::class)
+ unmockkObject(AppLogger)
+ }
+
+ private fun doc(name: String, isFile: Boolean = true) = mockk<DocumentFile>(relaxed = true) {
+ every { [email protected] } returns name
+ every { [email protected] } returns isFile
+ }
+
+ private fun cleanup(retentionCount: Int, vararg listed: DocumentFile) {
+ every { tree.listFiles() } returns arrayOf(*listed)
+ ExportFolder(context, dirUri).cleanup(AutoExportConfig(retentionCount = retentionCount))
+ }
+
+ /** The folder is the user's: a subfolder or another app's file in it is never Colota's to delete. */
+ @Test
+ fun `cleanup keeps the newest exports and leaves folders and foreign files alone`() {
+ val oldest = doc("colota_export_2026-10-01_1200.csv")
+ val older = doc("colota_export_2026-10-02_1200.csv")
+ val newer = doc("colota_export_2026-10-03_1200.csv")
+ val newest = doc("colota_export_2026-10-04_1200.gpx")
+ val folderSharingAName = doc("colota_export_2026-10-01_1200.csv", isFile = false)
+ val foreign = doc("notes.txt")
+
+ cleanup(2, oldest, older, newer, newest, folderSharingAName, foreign)
+
+ verify { oldest.delete() }
+ verify { older.delete() }
+ listOf(newer, newest, folderSharingAName, foreign).forEach { verify(exactly = 0) { it.delete() } }
+ }
+
+ /** A provider can hold two documents with one display name, and each counts against the limit. */
+ @Test
+ fun `two exports with one name are deleted one apiece`() {
+ val first = doc("colota_export_2026-10-01_1200.csv")
+ val second = doc("colota_export_2026-10-01_1200.csv")
+ val kept = doc("colota_export_2026-10-02_1200.csv")
+
+ cleanup(1, first, second, kept)
+
+ verify { first.delete() }
+ verify { second.delete() }
+ verify(exactly = 0) { kept.delete() }
+ }
+
+ @Test
+ fun `unlimited retention does not even list the folder`() {
+ ExportFolder(context, dirUri).cleanup(AutoExportConfig(retentionCount = 0))
+
+ verify(exactly = 0) { DocumentFile.fromTreeUri(any(), any()) }
+ }
+}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/BluetoothDeviceMonitorTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/BluetoothDeviceMonitorTest.kt
new file mode 100644
index 00000000..d35c985a
--- /dev/null
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/BluetoothDeviceMonitorTest.kt
@@ -0,0 +1,159 @@
+package com.Colota.service
+
+import android.bluetooth.BluetoothAdapter
+import android.bluetooth.BluetoothDevice
+import android.bluetooth.BluetoothManager
+import android.bluetooth.BluetoothProfile
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
+import com.Colota.util.AppLogger
+import io.mockk.*
+import org.junit.After
+import org.junit.Assert.*
+import org.junit.Before
+import org.junit.Test
+
+/** The stubbed android.jar reports SDK 0, so the receiver registers without the exported flag here. */
+class BluetoothDeviceMonitorTest {
+
+ private lateinit var context: Context
+ private val pushes = mutableListOf<Set<String>>()
+ private val receiver = slot<BroadcastReceiver>()
+ private lateinit var monitor: BluetoothDeviceMonitor
+
+ @Before
+ fun setUp() {
+ context = mockk(relaxed = true)
+ every { context.registerReceiver(capture(receiver), any<IntentFilter>()) } returns null
+ pushes.clear()
+ monitor = BluetoothDeviceMonitor(context) { pushes.add(it) }
+
+ mockkObject(AppLogger)
+ every { AppLogger.d(any(), any()) } just Runs
+ every { AppLogger.w(any(), any()) } just Runs
+ }
+
+ @After
+ fun tearDown() {
+ unmockkObject(AppLogger)
+ }
+
+ private fun adapter(enabled: Boolean): BluetoothAdapter {
+ val btAdapter = mockk<BluetoothAdapter>(relaxed = true) { every { isEnabled } returns enabled }
+ val manager = mockk<BluetoothManager> { every { adapter } returns btAdapter }
+ every { context.getSystemService(Context.BLUETOOTH_SERVICE) } returns manager
+ return btAdapter
+ }
+
+ private fun device(address: String) = mockk<BluetoothDevice> { every { [email protected] } returns address }
+
+ private fun aclIntent(action: String, address: String): Intent {
+ val device = device(address)
+ return mockk {
+ every { [email protected] } returns action
+ @Suppress("DEPRECATION")
+ every { getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) } returns device
+ }
+ }
+
+ @Test
+ fun `a phone without Bluetooth reports no devices and listens for none`() {
+ every { context.getSystemService(Context.BLUETOOTH_SERVICE) } returns null
+
+ monitor.start()
+
+ assertEquals(listOf(emptySet<String>()), pushes)
+ assertFalse(receiver.isCaptured)
+ }
+
+ @Test
+ fun `start seeds the devices already connected over A2DP and headset`() {
+ val adapter = adapter(enabled = true)
+ val car = device("aa:bb:cc:dd:ee:ff")
+ every { adapter.getProfileProxy(any(), any(), any()) } answers {
+ val profile = thirdArg<Int>()
+ val devices = if (profile == BluetoothProfile.HEADSET) listOf(car) else emptyList()
+ val proxy = mockk<BluetoothProfile> { every { connectedDevices } returns devices }
+ secondArg<BluetoothProfile.ServiceListener>().onServiceConnected(profile, proxy)
+ true
+ }
+
+ monitor.start()
+
+ verify { adapter.getProfileProxy(context, any(), BluetoothProfile.A2DP) }
+ verify { adapter.getProfileProxy(context, any(), BluetoothProfile.HEADSET) }
+ verify(exactly = 2) { adapter.closeProfileProxy(any(), any()) }
+ // Pushed once, after both proxies answered, so a half-read set never deactivates the profile.
+ assertEquals(listOf(setOf("AA:BB:CC:DD:EE:FF")), pushes)
+ }
+
+ @Test
+ fun `start still reports when a profile proxy is unavailable`() {
+ val adapter = adapter(enabled = true)
+ every { adapter.getProfileProxy(any(), any(), any()) } returns false
+
+ monitor.start()
+
+ assertEquals(listOf(emptySet<String>()), pushes)
+ }
+
+ @Test
+ fun `proxy results arriving after stop are dropped`() {
+ val adapter = adapter(enabled = true)
+ val listeners = mutableListOf<Pair<Int, BluetoothProfile.ServiceListener>>()
+ every { adapter.getProfileProxy(any(), any(), any()) } answers {
+ listeners.add(thirdArg<Int>() to secondArg<BluetoothProfile.ServiceListener>())
+ true
+ }
+ monitor.start()
+ monitor.stop()
+
+ val proxy = mockk<BluetoothProfile> { every { connectedDevices } returns listOf(device("AA:BB:CC:DD:EE:FF")) }
+ listeners.forEach { (profile, listener) -> listener.onServiceConnected(profile, proxy) }
+
+ assertTrue(pushes.isEmpty())
+ verify(exactly = 2) { adapter.closeProfileProxy(any(), proxy) }
+ }
+
+ @Test
+ fun `the receiver tracks devices connecting and disconnecting`() {
+ adapter(enabled = false)
+ monitor.start()
+
+ receiver.captured.onReceive(context, aclIntent(BluetoothDevice.ACTION_ACL_CONNECTED, "aa:bb:cc:dd:ee:ff"))
+ receiver.captured.onReceive(context, aclIntent(BluetoothDevice.ACTION_ACL_CONNECTED, "11:22:33:44:55:66"))
+ receiver.captured.onReceive(context, aclIntent(BluetoothDevice.ACTION_ACL_DISCONNECTED, "AA:BB:CC:DD:EE:FF"))
+
+ assertEquals(
+ listOf(emptySet(), setOf("AA:BB:CC:DD:EE:FF"), setOf("AA:BB:CC:DD:EE:FF", "11:22:33:44:55:66"), setOf("11:22:33:44:55:66")),
+ pushes
+ )
+ }
+
+ @Test
+ fun `turning Bluetooth off clears every connected device`() {
+ adapter(enabled = false)
+ monitor.start()
+ receiver.captured.onReceive(context, aclIntent(BluetoothDevice.ACTION_ACL_CONNECTED, "AA:BB:CC:DD:EE:FF"))
+
+ val off = mockk<Intent> {
+ every { action } returns BluetoothAdapter.ACTION_STATE_CHANGED
+ every { getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR) } returns BluetoothAdapter.STATE_TURNING_OFF
+ }
+ receiver.captured.onReceive(context, off)
+
+ assertEquals(emptySet<String>(), pushes.last())
+ }
+
+ @Test
+ fun `stop unregisters the receiver`() {
+ adapter(enabled = false)
+ monitor.start()
+
+ monitor.stop()
+
+ verify { context.unregisterReceiver(receiver.captured) }
+ }
+}
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/ConditionMonitorTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/ConditionMonitorTest.kt
index e427099e..27180d14 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/ConditionMonitorTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/ConditionMonitorTest.kt
@@ -5,10 +5,6 @@
package com.Colota.service
-import android.bluetooth.BluetoothAdapter
-import android.bluetooth.BluetoothDevice
-import android.bluetooth.BluetoothManager
-import android.bluetooth.BluetoothProfile
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
@@ -295,102 +291,7 @@ class ConditionMonitorTest {
monitor.start()
verify { mockProfileManager.onBluetoothDevicesChanged(emptySet()) }
- assertNull(getField(monitor, "bluetoothReceiver"))
- }
-
- @Test
- fun `start seeds the devices already connected over A2DP and headset`() {
- val adapter = mockBluetoothAdapter(enabled = true)
- val car = mockBluetoothDevice("aa:bb:cc:dd:ee:ff")
- every { adapter.getProfileProxy(any(), any(), any()) } answers {
- val profile = thirdArg<Int>()
- val devices = if (profile == BluetoothProfile.HEADSET) listOf(car) else emptyList()
- val proxy = mockk<BluetoothProfile> { every { connectedDevices } returns devices }
- secondArg<BluetoothProfile.ServiceListener>().onServiceConnected(profile, proxy)
- true
- }
-
- monitor.start()
-
- verify { adapter.getProfileProxy(mockContext, any(), BluetoothProfile.A2DP) }
- verify { adapter.getProfileProxy(mockContext, any(), BluetoothProfile.HEADSET) }
- verify(exactly = 2) { adapter.closeProfileProxy(any(), any()) }
- // Pushed once, after both proxies answered, so a half-read set never deactivates the profile.
- verify(exactly = 1) { mockProfileManager.onBluetoothDevicesChanged(setOf("AA:BB:CC:DD:EE:FF")) }
- verify(exactly = 1) { mockProfileManager.onBluetoothDevicesChanged(any()) }
- }
-
- @Test
- fun `start still reports when a profile proxy is unavailable`() {
- val adapter = mockBluetoothAdapter(enabled = true)
- every { adapter.getProfileProxy(any(), any(), any()) } returns false
-
- monitor.start()
-
- verify(exactly = 1) { mockProfileManager.onBluetoothDevicesChanged(emptySet()) }
- }
-
- @Test
- fun `proxy results arriving after stop are dropped`() {
- val adapter = mockBluetoothAdapter(enabled = true)
- val listeners = mutableListOf<Pair<Int, BluetoothProfile.ServiceListener>>()
- every { adapter.getProfileProxy(any(), any(), any()) } answers {
- listeners.add(thirdArg<Int>() to secondArg<BluetoothProfile.ServiceListener>())
- true
- }
- monitor.start()
- monitor.stop()
-
- val proxy = mockk<BluetoothProfile> { every { connectedDevices } returns listOf(mockBluetoothDevice("AA:BB:CC:DD:EE:FF")) }
- listeners.forEach { (profile, listener) -> listener.onServiceConnected(profile, proxy) }
-
- verify(exactly = 0) { mockProfileManager.onBluetoothDevicesChanged(any()) }
- verify(exactly = 2) { adapter.closeProfileProxy(any(), proxy) }
- }
-
- @Test
- fun `bluetooth receiver tracks devices connecting and disconnecting`() {
- mockBluetoothAdapter(enabled = false)
- monitor.start()
- val receiver = getField(monitor, "bluetoothReceiver") as BroadcastReceiver
-
- receiver.onReceive(mockContext, aclIntent(BluetoothDevice.ACTION_ACL_CONNECTED, "aa:bb:cc:dd:ee:ff"))
- verify { mockProfileManager.onBluetoothDevicesChanged(setOf("AA:BB:CC:DD:EE:FF")) }
-
- receiver.onReceive(mockContext, aclIntent(BluetoothDevice.ACTION_ACL_CONNECTED, "11:22:33:44:55:66"))
- verify { mockProfileManager.onBluetoothDevicesChanged(setOf("AA:BB:CC:DD:EE:FF", "11:22:33:44:55:66")) }
-
- receiver.onReceive(mockContext, aclIntent(BluetoothDevice.ACTION_ACL_DISCONNECTED, "AA:BB:CC:DD:EE:FF"))
- verify { mockProfileManager.onBluetoothDevicesChanged(setOf("11:22:33:44:55:66")) }
- }
-
- @Test
- fun `turning Bluetooth off clears every connected device`() {
- mockBluetoothAdapter(enabled = false)
- monitor.start()
- val receiver = getField(monitor, "bluetoothReceiver") as BroadcastReceiver
- receiver.onReceive(mockContext, aclIntent(BluetoothDevice.ACTION_ACL_CONNECTED, "AA:BB:CC:DD:EE:FF"))
-
- val off = mockk<Intent> {
- every { action } returns BluetoothAdapter.ACTION_STATE_CHANGED
- every { getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR) } returns BluetoothAdapter.STATE_TURNING_OFF
- }
- receiver.onReceive(mockContext, off)
-
- // Once from the disabled adapter at start, once from the state change.
- verify(exactly = 2) { mockProfileManager.onBluetoothDevicesChanged(emptySet()) }
- }
-
- @Test
- fun `stop unregisters the bluetooth receiver`() {
- mockBluetoothAdapter(enabled = false)
- monitor.start()
- val receiver = getField(monitor, "bluetoothReceiver") as BroadcastReceiver
-
- monitor.stop()
-
- verify { mockContext.unregisterReceiver(receiver) }
- assertNull(getField(monitor, "bluetoothReceiver"))
+ verify(exactly = 0) { mockContext.registerReceiver(any(), any<IntentFilter>()) }
}
@Test
@@ -399,7 +300,6 @@ class ConditionMonitorTest {
monitor.start()
verify(exactly = 0) { mockContext.getSystemService(Context.BLUETOOTH_SERVICE) }
- assertNull(getField(monitor, "bluetoothReceiver"))
}
// ========================================================================
@@ -556,7 +456,7 @@ class ConditionMonitorTest {
setField(spy, "networkMonitor", mockNetworkMonitor)
setField(spy, "profileManager", mockProfileManager)
setField(spy, "mainHandler", mockHandler)
- setField(spy, "connectedBluetoothAddresses", mutableSetOf<String>())
+ setField(spy, "bluetoothMonitor", BluetoothDeviceMonitor(mockContext) { mockProfileManager.onBluetoothDevicesChanged(it) })
// Stub car connection methods — CarConnection cannot be constructed in unit tests
// because CarConnectionTypeLiveData's static initializer uses Uri.Builder which
@@ -567,29 +467,6 @@ class ConditionMonitorTest {
return spy
}
- private fun mockBluetoothAdapter(enabled: Boolean): BluetoothAdapter {
- every { mockProfileManager.getNeededConditionTypes() } returns setOf(ProfileConstants.CONDITION_BLUETOOTH_DEVICE)
- val btAdapter = mockk<BluetoothAdapter>(relaxed = true) {
- every { isEnabled } returns enabled
- }
- val manager = mockk<BluetoothManager> { every { adapter } returns btAdapter }
- every { mockContext.getSystemService(Context.BLUETOOTH_SERVICE) } returns manager
- return btAdapter
- }
-
- private fun mockBluetoothDevice(address: String) = mockk<BluetoothDevice> {
- every { [email protected] } returns address
- }
-
- private fun aclIntent(action: String, address: String): Intent {
- val device = mockBluetoothDevice(address)
- return mockk {
- every { [email protected] } returns action
- @Suppress("DEPRECATION")
- every { getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) } returns device
- }
- }
-
private fun mockBatteryStatus(status: Int) {
val batteryIntent = mockk<Intent> {
every { getIntExtra(BatteryManager.EXTRA_STATUS, -1) } returns status