Colota - Android GPS Location tracker
Add tracking profiles with automatic condition-based GPS switching
Max Dietrich9295180f5d72
diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsxindex 7d9cc5d4..935f8802 100644--- a/apps/mobile/App.tsx+++ b/apps/mobile/App.tsx@@ -20,7 +20,9 @@ import {DataManagementScreen,LocationHistoryScreen,ExportDataScreen,- AboutScreen+ AboutScreen,+ TrackingProfilesScreen,+ ProfileEditorScreen} from "./src/screens/"const Stack = createNativeStackNavigator()@@ -66,6 +68,16 @@ const SCREEN_CONFIG = [component: DataManagementScreen,title: "Data Management"},+ {+ name: "Tracking Profiles",+ component: TrackingProfilesScreen,+ title: "Tracking Profiles"+ },+ {+ name: "Profile Editor",+ component: ProfileEditorScreen,+ title: "Profile Editor"+ },{name: "About Colota",component: AboutScreen,diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.ktindex f4e5e6d3..b89a537f 100644--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt@@ -9,8 +9,13 @@ import android.content.Intentimport com.Colota.BuildConfigimport com.Colota.data.DatabaseHelperimport com.Colota.data.GeofenceHelper+import com.Colota.data.ProfileHelperimport com.Colota.service.LocationForegroundServiceimport com.Colota.service.ServiceConfig+import com.Colota.service.getDoubleOrNull+import com.Colota.service.getIntOrNull+import com.Colota.service.getStringOrNull+import com.Colota.service.getBooleanOrNullimport com.Colota.sync.NetworkManagerimport com.Colota.sync.PayloadBuilderimport com.Colota.util.DeviceInfoHelper@@ -38,6 +43,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :private val fileOps = FileOperations(reactContext)private val deviceInfo = DeviceInfoHelper(reactContext)private val geofenceHelper = GeofenceHelper(reactContext)+ private val profileHelper = ProfileHelper(reactContext)private val secureStorage = SecureStorageHelper.getInstance(reactContext)private val networkManager = NetworkManager(reactContext)@@ -133,6 +139,30 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :}}+ /** Emits profile switch events to JS when a tracking profile activates/deactivates. */+ @JvmStatic+ fun sendProfileSwitchEvent(profileName: String?, profileId: Int?): Boolean {+ val context = reactContextRef.get() ?: return false+ if (!context.hasActiveCatalystInstance()) return false++ return try {+ val params = Arguments.createMap().apply {+ if (profileName != null) putString("profileName", profileName)+ else putNull("profileName")+ if (profileId != null) putInt("profileId", profileId)+ else putNull("profileId")+ putBoolean("isDefault", profileName == null)+ }+ context+ .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)+ .emit("onProfileSwitch", params)+ true+ } catch (e: Exception) {+ Log.e(TAG, "Failed to send profile switch event", e)+ false+ }+ }+/** Emits pause zone entry/exit events for the JS geofence UI. */@JvmStaticfun sendPauseZoneEvent(entered: Boolean, zoneName: String?): Boolean {@@ -417,6 +447,104 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :}}+ // ========================================================================+ // TRACKING PROFILES+ // ========================================================================++ @ReactMethod+ fun getProfiles(promise: Promise) = executeAsync(promise) {+ profileHelper.getProfilesAsArray()+ }++ @ReactMethod+ fun createProfile(config: ReadableMap, promise: Promise) = executeAsync(promise) {+ val id = profileHelper.insertProfile(+ name = config.getString("name") ?: "",+ intervalMs = config.getDouble("intervalMs").toLong(),+ minUpdateDistance = config.getDouble("minUpdateDistance").toFloat(),+ syncIntervalSeconds = config.getInt("syncIntervalSeconds"),+ priority = config.getInt("priority"),+ conditionType = config.getString("conditionType") ?: "charging",+ speedThreshold = if (config.hasKey("speedThreshold") && !config.isNull("speedThreshold"))+ config.getDouble("speedThreshold").toFloat() else null,+ deactivationDelaySeconds = config.getInt("deactivationDelaySeconds")+ )+ if (id > 0) {+ profileHelper.invalidateCache()+ triggerProfileRecheck()+ }+ id+ }++ @ReactMethod+ fun updateProfile(config: ReadableMap, promise: Promise) = executeAsync(promise) {+ val id = config.getInt("id")+ val result = profileHelper.updateProfile(+ id = id,+ name = config.getStringOrNull("name"),+ intervalMs = config.getDoubleOrNull("intervalMs")?.toLong(),+ minUpdateDistance = config.getDoubleOrNull("minUpdateDistance")?.toFloat(),+ syncIntervalSeconds = config.getIntOrNull("syncIntervalSeconds"),+ priority = config.getIntOrNull("priority"),+ conditionType = config.getStringOrNull("conditionType"),+ speedThreshold = if (config.hasKey("speedThreshold") && !config.isNull("speedThreshold"))+ config.getDouble("speedThreshold").toFloat() else null,+ hasSpeedThreshold = config.hasKey("speedThreshold"),+ deactivationDelaySeconds = config.getIntOrNull("deactivationDelaySeconds"),+ enabled = config.getBooleanOrNull("enabled")+ )+ if (result) {+ profileHelper.invalidateCache()+ triggerProfileRecheck()+ }+ result+ }++ @ReactMethod+ fun deleteProfile(id: Int, promise: Promise) = executeAsync(promise) {+ val result = profileHelper.deleteProfile(id)+ if (result) {+ profileHelper.invalidateCache()+ triggerProfileRecheck()+ }+ result+ }++ @ReactMethod+ fun getActiveProfile(promise: Promise) {+ // Active profile state is managed by the foreground service's ProfileManager.+ // Return null if service isn't running — the JS side listens for onProfileSwitch events.+ promise.resolve(null)+ }++ @ReactMethod+ fun getTripEvents(startTimestamp: Double, endTimestamp: Double, promise: Promise) =+ executeAsync(promise) {+ profileHelper.getTripEventsAsArray(startTimestamp.toLong(), endTimestamp.toLong())+ }++ @ReactMethod+ fun recheckProfiles(promise: Promise) {+ try {+ triggerProfileRecheck()+ promise.resolve(true)+ } catch (e: Exception) {+ Log.e(TAG, "Profile recheck failed", e)+ promise.reject("RECHECK_ERROR", e.message, e)+ }+ }++ private fun triggerProfileRecheck() {+ val isTracking = dbHelper.getSetting("tracking_enabled", "false") == "true"+ if (isTracking) {+ try {+ startServiceWithAction(LocationForegroundService.ACTION_RECHECK_PROFILES)+ } catch (e: Exception) {+ Log.w(TAG, "Profile recheck skipped: service not running", e)+ }+ }+ }+@ReactMethodfun recheckZoneSettings(promise: Promise) {triggerZoneRecheck()diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.ktindex 796d3f56..e7f2ffa8 100644--- a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt@@ -25,12 +25,14 @@ class DatabaseHelper private constructor(context: Context) :companion object {private const val DATABASE_NAME = "Colota.db"- private const val DATABASE_VERSION = 1+ private const val DATABASE_VERSION = 2const val TABLE_LOCATIONS = "locations"const val TABLE_QUEUE = "queue"const val TABLE_SETTINGS = "settings"const val TABLE_GEOFENCES = "geofences"+ const val TABLE_PROFILES = "tracking_profiles"+ const val TABLE_TRIP_EVENTS = "trip_events"private val DEFAULT_FIELD_MAP = mapOf("lat" to "lat", "lon" to "lon", "acc" to "acc",@@ -111,6 +113,8 @@ class DatabaseHelper private constructor(context: Context) :)""")+ createProfileTables(db)+db.execSQL("CREATE INDEX idx_queue_created ON $TABLE_QUEUE(created_at)")db.execSQL("CREATE INDEX idx_queue_location ON $TABLE_QUEUE(location_id)")db.execSQL("CREATE INDEX idx_locations_timestamp ON $TABLE_LOCATIONS(timestamp DESC)")@@ -166,8 +170,44 @@ class DatabaseHelper private constructor(context: Context) :db.rawQuery("PRAGMA busy_timeout = 5000", null).use { it.moveToFirst() }}+ private fun createProfileTables(db: SQLiteDatabase) {+ db.execSQL("""+ CREATE TABLE $TABLE_PROFILES (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ name TEXT NOT NULL,+ interval_ms INTEGER NOT NULL,+ min_update_distance REAL NOT NULL,+ sync_interval_seconds INTEGER NOT NULL,+ priority INTEGER NOT NULL DEFAULT 0,+ condition_type TEXT NOT NULL,+ speed_threshold REAL,+ deactivation_delay_seconds INTEGER NOT NULL DEFAULT 30,+ enabled INTEGER NOT NULL DEFAULT 1,+ created_at INTEGER NOT NULL+ )+ """)++ db.execSQL("""+ CREATE TABLE $TABLE_TRIP_EVENTS (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ profile_id INTEGER,+ profile_name TEXT NOT NULL,+ event_type TEXT NOT NULL,+ latitude REAL,+ longitude REAL,+ timestamp INTEGER NOT NULL,+ FOREIGN KEY (profile_id) REFERENCES $TABLE_PROFILES(id) ON DELETE SET NULL+ )+ """)++ db.execSQL("CREATE INDEX idx_profiles_enabled ON $TABLE_PROFILES(enabled, priority DESC)")+ db.execSQL("CREATE INDEX idx_trip_events_timestamp ON $TABLE_TRIP_EVENTS(timestamp DESC)")+ }+override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {- // Future migrations go here+ if (oldVersion < 2) {+ createProfileTables(db)+ }}override fun onOpen(db: SQLiteDatabase) {@@ -249,7 +289,7 @@ class DatabaseHelper private constructor(context: Context) :}}- private val ALLOWED_TABLES = setOf(TABLE_LOCATIONS, TABLE_QUEUE, TABLE_SETTINGS, TABLE_GEOFENCES)+ private val ALLOWED_TABLES = setOf(TABLE_LOCATIONS, TABLE_QUEUE, TABLE_SETTINGS, TABLE_GEOFENCES, TABLE_PROFILES, TABLE_TRIP_EVENTS)fun getTableData(tableName: String, limit: Int, offset: Int): List<Map<String, Any?>> {require(tableName in ALLOWED_TABLES) { "Invalid table name: $tableName" }diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.ktnew file mode 100644index 00000000..550c4c8a--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/data/ProfileHelper.kt@@ -0,0 +1,290 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.data++import android.content.ContentValues+import com.Colota.BuildConfig+import com.Colota.util.TimedCache+import android.content.Context+import android.util.Log+import com.facebook.react.bridge.Arguments+import com.facebook.react.bridge.WritableArray++class ProfileHelper(private val context: Context) {++ private val dbHelper by lazy { DatabaseHelper.getInstance(context) }++ private val profileCache = TimedCache(30000L) { loadEnabledProfilesFromDB() }++ data class CachedProfile(+ val id: Int,+ val name: String,+ val intervalMs: Long,+ val minUpdateDistance: Float,+ val syncIntervalSeconds: Int,+ val priority: Int,+ val conditionType: String,+ val speedThreshold: Float?,+ val deactivationDelaySeconds: Int+ )++ companion object {+ private const val TAG = "ProfileHelper"+ }++ fun invalidateCache() {+ profileCache.invalidate()+ if (BuildConfig.DEBUG) {+ Log.d(TAG, "Profile cache invalidated")+ }+ }++ fun getEnabledProfiles(): List<CachedProfile> = profileCache.get()++ private fun loadEnabledProfilesFromDB(): List<CachedProfile> {+ return try {+ val profiles = mutableListOf<CachedProfile>()+ dbHelper.readableDatabase.query(+ DatabaseHelper.TABLE_PROFILES,+ arrayOf(+ "id", "name", "interval_ms", "min_update_distance",+ "sync_interval_seconds", "priority", "condition_type",+ "speed_threshold", "deactivation_delay_seconds"+ ),+ "enabled = 1",+ null, null, null,+ "priority DESC"+ ).use { cursor ->+ val idIdx = cursor.getColumnIndexOrThrow("id")+ val nameIdx = cursor.getColumnIndexOrThrow("name")+ val intervalIdx = cursor.getColumnIndexOrThrow("interval_ms")+ val distIdx = cursor.getColumnIndexOrThrow("min_update_distance")+ val syncIdx = cursor.getColumnIndexOrThrow("sync_interval_seconds")+ val prioIdx = cursor.getColumnIndexOrThrow("priority")+ val condIdx = cursor.getColumnIndexOrThrow("condition_type")+ val speedIdx = cursor.getColumnIndexOrThrow("speed_threshold")+ val delayIdx = cursor.getColumnIndexOrThrow("deactivation_delay_seconds")++ while (cursor.moveToNext()) {+ profiles.add(CachedProfile(+ id = cursor.getInt(idIdx),+ name = cursor.getString(nameIdx),+ intervalMs = cursor.getLong(intervalIdx),+ minUpdateDistance = cursor.getFloat(distIdx),+ syncIntervalSeconds = cursor.getInt(syncIdx),+ priority = cursor.getInt(prioIdx),+ conditionType = cursor.getString(condIdx),+ speedThreshold = if (cursor.isNull(speedIdx)) null else cursor.getFloat(speedIdx),+ deactivationDelaySeconds = cursor.getInt(delayIdx)+ ))+ }+ }+ profiles+ } catch (e: Exception) {+ Log.e(TAG, "Failed to load profiles", e)+ emptyList()+ }+ }++ fun getProfilesAsArray(): WritableArray {+ val array = Arguments.createArray()++ try {+ dbHelper.readableDatabase.query(+ DatabaseHelper.TABLE_PROFILES,+ null, null, null, null, null,+ "priority DESC"+ ).use { cursor ->+ val idIdx = cursor.getColumnIndexOrThrow("id")+ val nameIdx = cursor.getColumnIndexOrThrow("name")+ val intervalIdx = cursor.getColumnIndexOrThrow("interval_ms")+ val distIdx = cursor.getColumnIndexOrThrow("min_update_distance")+ val syncIdx = cursor.getColumnIndexOrThrow("sync_interval_seconds")+ val prioIdx = cursor.getColumnIndexOrThrow("priority")+ val condIdx = cursor.getColumnIndexOrThrow("condition_type")+ val speedIdx = cursor.getColumnIndexOrThrow("speed_threshold")+ val delayIdx = cursor.getColumnIndexOrThrow("deactivation_delay_seconds")+ val enabledIdx = cursor.getColumnIndexOrThrow("enabled")+ val createdIdx = cursor.getColumnIndexOrThrow("created_at")++ while (cursor.moveToNext()) {+ array.pushMap(Arguments.createMap().apply {+ putInt("id", cursor.getInt(idIdx))+ putString("name", cursor.getString(nameIdx))+ putDouble("intervalMs", cursor.getLong(intervalIdx).toDouble())+ putDouble("minUpdateDistance", cursor.getFloat(distIdx).toDouble())+ putInt("syncIntervalSeconds", cursor.getInt(syncIdx))+ putInt("priority", cursor.getInt(prioIdx))+ putString("conditionType", cursor.getString(condIdx))+ if (cursor.isNull(speedIdx)) {+ putNull("speedThreshold")+ } else {+ putDouble("speedThreshold", cursor.getFloat(speedIdx).toDouble())+ }+ putInt("deactivationDelaySeconds", cursor.getInt(delayIdx))+ putBoolean("enabled", cursor.getInt(enabledIdx) == 1)+ putDouble("createdAt", cursor.getLong(createdIdx).toDouble())+ })+ }+ }+ } catch (e: Exception) {+ Log.e(TAG, "Failed to load profiles as array", e)+ }++ return array+ }++ fun insertProfile(+ name: String,+ intervalMs: Long,+ minUpdateDistance: Float,+ syncIntervalSeconds: Int,+ priority: Int,+ conditionType: String,+ speedThreshold: Float?,+ deactivationDelaySeconds: Int+ ): Int {+ val values = ContentValues().apply {+ put("name", name)+ put("interval_ms", intervalMs)+ put("min_update_distance", minUpdateDistance)+ put("sync_interval_seconds", syncIntervalSeconds)+ put("priority", priority)+ put("condition_type", conditionType)+ if (speedThreshold != null) {+ put("speed_threshold", speedThreshold)+ } else {+ putNull("speed_threshold")+ }+ put("deactivation_delay_seconds", deactivationDelaySeconds)+ put("enabled", 1)+ put("created_at", System.currentTimeMillis() / 1000)+ }++ return dbHelper.writableDatabase+ .insert(DatabaseHelper.TABLE_PROFILES, null, values)+ .toInt()+ }++ fun updateProfile(+ id: Int,+ name: String?,+ intervalMs: Long?,+ minUpdateDistance: Float?,+ syncIntervalSeconds: Int?,+ priority: Int?,+ conditionType: String?,+ speedThreshold: Float?,+ hasSpeedThreshold: Boolean,+ deactivationDelaySeconds: Int?,+ enabled: Boolean?+ ): Boolean {+ val values = ContentValues().apply {+ name?.let { put("name", it) }+ intervalMs?.let { put("interval_ms", it) }+ minUpdateDistance?.let { put("min_update_distance", it) }+ syncIntervalSeconds?.let { put("sync_interval_seconds", it) }+ priority?.let { put("priority", it) }+ conditionType?.let { put("condition_type", it) }+ if (hasSpeedThreshold) {+ if (speedThreshold != null) {+ put("speed_threshold", speedThreshold)+ } else {+ putNull("speed_threshold")+ }+ }+ deactivationDelaySeconds?.let { put("deactivation_delay_seconds", it) }+ enabled?.let { put("enabled", if (it) 1 else 0) }+ }++ if (values.size() == 0) return false++ return dbHelper.writableDatabase.update(+ DatabaseHelper.TABLE_PROFILES,+ values,+ "id = ?",+ arrayOf(id.toString())+ ) > 0+ }++ fun deleteProfile(id: Int): Boolean {+ return dbHelper.writableDatabase.delete(+ DatabaseHelper.TABLE_PROFILES,+ "id = ?",+ arrayOf(id.toString())+ ) > 0+ }++ fun logTripEvent(+ profileId: Int?,+ profileName: String,+ eventType: String,+ latitude: Double?,+ longitude: Double?,+ timestamp: Long+ ) {+ try {+ val values = ContentValues().apply {+ if (profileId != null) {+ put("profile_id", profileId)+ } else {+ putNull("profile_id")+ }+ put("profile_name", profileName)+ put("event_type", eventType)+ if (latitude != null) put("latitude", latitude) else putNull("latitude")+ if (longitude != null) put("longitude", longitude) else putNull("longitude")+ put("timestamp", timestamp)+ }++ dbHelper.writableDatabase.insert(DatabaseHelper.TABLE_TRIP_EVENTS, null, values)+ } catch (e: Exception) {+ Log.e(TAG, "Failed to log trip event", e)+ }+ }++ fun getTripEventsAsArray(startTimestamp: Long, endTimestamp: Long): WritableArray {+ val array = Arguments.createArray()++ try {+ dbHelper.readableDatabase.query(+ DatabaseHelper.TABLE_TRIP_EVENTS,+ null,+ "timestamp >= ? AND timestamp <= ?",+ arrayOf(startTimestamp.toString(), endTimestamp.toString()),+ null, null,+ "timestamp DESC"+ ).use { cursor ->+ val idIdx = cursor.getColumnIndexOrThrow("id")+ val profIdIdx = cursor.getColumnIndexOrThrow("profile_id")+ val profNameIdx = cursor.getColumnIndexOrThrow("profile_name")+ val typeIdx = cursor.getColumnIndexOrThrow("event_type")+ val latIdx = cursor.getColumnIndexOrThrow("latitude")+ val lonIdx = cursor.getColumnIndexOrThrow("longitude")+ val tsIdx = cursor.getColumnIndexOrThrow("timestamp")++ while (cursor.moveToNext()) {+ array.pushMap(Arguments.createMap().apply {+ putInt("id", cursor.getInt(idIdx))+ if (cursor.isNull(profIdIdx)) putNull("profileId")+ else putInt("profileId", cursor.getInt(profIdIdx))+ putString("profileName", cursor.getString(profNameIdx))+ putString("eventType", cursor.getString(typeIdx))+ if (cursor.isNull(latIdx)) putNull("latitude")+ else putDouble("latitude", cursor.getDouble(latIdx))+ if (cursor.isNull(lonIdx)) putNull("longitude")+ else putDouble("longitude", cursor.getDouble(lonIdx))+ putDouble("timestamp", cursor.getLong(tsIdx).toDouble())+ })+ }+ }+ } catch (e: Exception) {+ Log.e(TAG, "Failed to load trip events", e)+ }++ return array+ }+}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.ktnew file mode 100644index 00000000..e56725c2--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ConditionMonitor.kt@@ -0,0 +1,113 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.service++import android.app.UiModeManager+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.content.res.Configuration+import android.os.BatteryManager+import android.util.Log+import com.Colota.BuildConfig++/**+ * Monitors device conditions (charging state, Android Auto / car mode)+ * and notifies ProfileManager when conditions change.+ *+ * All receivers are registered programmatically so they only run while+ * the foreground service is active.+ */+class ConditionMonitor(+ private val context: Context,+ private val profileManager: ProfileManager+) {+ companion object {+ private const val TAG = "ConditionMonitor"+ }++ private var chargingReceiver: BroadcastReceiver? = null+ private var carModeReceiver: BroadcastReceiver? = null++ fun start() {+ registerChargingMonitor()+ registerCarModeMonitor()++ // Read initial states+ profileManager.onChargingStateChanged(readCurrentChargingState())+ profileManager.onCarModeStateChanged(readCurrentCarModeState())++ if (BuildConfig.DEBUG) {+ Log.d(TAG, "Condition monitors started — charging: ${readCurrentChargingState()}, carMode: ${readCurrentCarModeState()}")+ }+ }++ fun stop() {+ chargingReceiver?.let {+ try { context.unregisterReceiver(it) } catch (_: Exception) {}+ }+ chargingReceiver = null++ carModeReceiver?.let {+ try { context.unregisterReceiver(it) } catch (_: Exception) {}+ }+ carModeReceiver = null++ if (BuildConfig.DEBUG) {+ Log.d(TAG, "Condition monitors stopped")+ }+ }++ private fun registerChargingMonitor() {+ chargingReceiver = object : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ when (intent.action) {+ Intent.ACTION_POWER_CONNECTED -> {+ if (BuildConfig.DEBUG) Log.d(TAG, "Power connected")+ profileManager.onChargingStateChanged(true)+ }+ Intent.ACTION_POWER_DISCONNECTED -> {+ if (BuildConfig.DEBUG) Log.d(TAG, "Power disconnected")+ profileManager.onChargingStateChanged(false)+ }+ }+ }+ }++ val filter = IntentFilter().apply {+ addAction(Intent.ACTION_POWER_CONNECTED)+ addAction(Intent.ACTION_POWER_DISCONNECTED)+ }+ context.registerReceiver(chargingReceiver, filter)+ }++ private fun registerCarModeMonitor() {+ carModeReceiver = object : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ if (intent.action == Intent.ACTION_CONFIGURATION_CHANGED) {+ val isCarMode = readCurrentCarModeState()+ if (BuildConfig.DEBUG) Log.d(TAG, "Configuration changed — carMode: $isCarMode")+ profileManager.onCarModeStateChanged(isCarMode)+ }+ }+ }++ context.registerReceiver(carModeReceiver, IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED))+ }++ private fun readCurrentChargingState(): Boolean {+ val batteryIntent = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))+ val status = batteryIntent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1+ return status == BatteryManager.BATTERY_STATUS_CHARGING ||+ status == BatteryManager.BATTERY_STATUS_FULL+ }++ private fun readCurrentCarModeState(): Boolean {+ val uiModeManager = context.getSystemService(Context.UI_MODE_SERVICE) as? UiModeManager+ return uiModeManager?.currentModeType == Configuration.UI_MODE_TYPE_CAR+ }+}diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.ktindex b1ea0d19..aea29b7e 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt@@ -10,6 +10,7 @@ import com.Colota.BuildConfigimport com.Colota.bridge.LocationServiceModuleimport com.Colota.data.DatabaseHelperimport com.Colota.data.GeofenceHelper+import com.Colota.data.ProfileHelperimport com.Colota.sync.NetworkManagerimport com.Colota.sync.PayloadBuilderimport com.Colota.sync.SyncManager@@ -39,6 +40,9 @@ class LocationForegroundService : Service() {private lateinit var geofenceHelper: GeofenceHelperprivate lateinit var secureStorage: SecureStorageHelperprivate lateinit var syncManager: SyncManager+ private lateinit var profileHelper: ProfileHelper+ private lateinit var profileManager: ProfileManager+ private lateinit var conditionMonitor: ConditionMonitor@Volatile private var serviceScope: CoroutineScope? = null@Volatile private var locationUpdateCallback: LocationUpdateCallback? = null@@ -56,13 +60,15 @@ class LocationForegroundService : Service() {const val ACTION_RECHECK_ZONE = "com.Colota.RECHECK_PAUSE_ZONE"const val ACTION_FORCE_EXIT_ZONE = "com.Colota.FORCE_EXIT_ZONE"const val ACTION_REFRESH_NOTIFICATION = "com.Colota.REFRESH_NOTIFICATION"+ const val ACTION_RECHECK_PROFILES = "com.Colota.RECHECK_PROFILES"/** Actions that skip config reload and preserve current notification state. */private val LIGHTWEIGHT_ACTIONS = setOf(ACTION_MANUAL_FLUSH,ACTION_RECHECK_ZONE,ACTION_FORCE_EXIT_ZONE,- ACTION_REFRESH_NOTIFICATION+ ACTION_REFRESH_NOTIFICATION,+ ACTION_RECHECK_PROFILES)}@@ -80,6 +86,11 @@ class LocationForegroundService : Service() {geofenceHelper = GeofenceHelper(this)secureStorage = SecureStorageHelper.getInstance(this)syncManager = SyncManager(dbHelper, networkManager, serviceScope!!)+ profileHelper = ProfileHelper(this)+ profileManager = ProfileManager(profileHelper, serviceScope!!) { interval, distance, syncInterval, profileName, _ ->+ applyProfileConfig(interval, distance, syncInterval, profileName)+ }+ conditionMonitor = ConditionMonitor(this, profileManager)notificationHelper = NotificationHelper(this, notificationManager)notificationHelper.createChannel()@@ -149,6 +160,10 @@ class LocationForegroundService : Service() {handleZoneRecheckAction()return START_STICKY}+ ACTION_RECHECK_PROFILES -> {+ profileManager.invalidateProfiles()+ return START_STICKY+ }ACTION_MANUAL_FLUSH -> {serviceScope?.launch {syncManager.manualFlush()@@ -170,6 +185,9 @@ class LocationForegroundService : Service() {syncManager.manualFlush()}}++ // Start condition monitors for profile-based config switching+ conditionMonitor.start()}}@@ -177,6 +195,7 @@ class LocationForegroundService : Service() {}override fun onDestroy() {+ conditionMonitor.stop()stopLocationUpdates()syncManager.stopPeriodicSync()@@ -316,6 +335,10 @@ class LocationForegroundService : Service() {}private fun handleLocationUpdate(location: android.location.Location) {+ // Feed location to profile manager for speed-based condition evaluation+ // (must run before accuracy filter so speed data is always captured)+ profileManager.onLocationUpdate(location)+if (config.filterInaccurateLocations && location.accuracy > config.accuracyThreshold) {return}@@ -470,6 +493,40 @@ class LocationForegroundService : Service() {stopSelf()}+ /**+ * Dynamically switches GPS interval and sync config when a profile activates/deactivates.+ * No full service restart — just re-requests location updates with new parameters.+ */+ private fun applyProfileConfig(interval: Long, distance: Float, syncInterval: Int, profileName: String?) {+ config = config.copy(+ interval = interval,+ minUpdateDistance = distance,+ syncIntervalSeconds = syncInterval+ )++ syncManager.updateConfig(+ endpoint = config.endpoint,+ syncIntervalSeconds = syncInterval,+ retryIntervalSeconds = config.retryIntervalSeconds,+ maxRetries = config.maxRetries,+ isOfflineMode = config.isOfflineMode,+ isWifiOnlySync = config.isWifiOnlySync,+ authHeaders = secureStorage.getAuthHeaders(),+ httpMethod = config.httpMethod+ )++ serviceScope?.launch {+ withContext(Dispatchers.Main) {+ stopLocationUpdates()+ setupLocationUpdates()+ }+ }++ if (BuildConfig.DEBUG) {+ Log.i(TAG, "Profile config applied: ${profileName ?: "default"} — interval=${interval}ms, distance=${distance}m, sync=${syncInterval}s")+ }+ }+private fun loadConfigFromIntent(intent: Intent?) {config = if (intent != null) {ServiceConfig.fromIntent(intent, dbHelper)@@ -488,6 +545,11 @@ class LocationForegroundService : Service() {httpMethod = config.httpMethod)+ // Store default values so ProfileManager can revert when no profile matches+ profileManager.defaultInterval = config.interval+ profileManager.defaultDistance = config.minUpdateDistance+ profileManager.defaultSyncInterval = config.syncIntervalSeconds+config.fieldMap?.let {if (it.isNotBlank()) fieldMap = payloadBuilder.parseFieldMap(it)}diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.ktnew file mode 100644index 00000000..1afab052--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/service/ProfileManager.kt@@ -0,0 +1,225 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.service++import android.location.Location+import android.util.Log+import com.Colota.BuildConfig+import com.Colota.bridge.LocationServiceModule+import com.Colota.data.ProfileHelper+import kotlinx.coroutines.*++/**+ * Evaluates tracking profile conditions and triggers config switches.+ *+ * When a profile's conditions match, its GPS interval / sync settings override+ * the default config. When conditions stop matching, a configurable deactivation+ * delay (hysteresis) prevents rapid switching before reverting to defaults.+ *+ * @param profileHelper CRUD access to profile database+ * @param scope Coroutine scope for deactivation delay timers+ * @param onConfigSwitch Callback to apply new interval/distance/sync params+ */+class ProfileManager(+ private val profileHelper: ProfileHelper,+ private val scope: CoroutineScope,+ private val onConfigSwitch: (interval: Long, distance: Float, syncInterval: Int, profileName: String?, profileId: Int?) -> Unit+) {+ companion object {+ private const val TAG = "ProfileManager"+ private const val SPEED_BUFFER_SIZE = 5+ }++ // Default config values (set by the service after loading config)+ @Volatile var defaultInterval: Long = 5000L+ @Volatile var defaultDistance: Float = 0f+ @Volatile var defaultSyncInterval: Int = 0++ // Current active profile (null = using default settings)+ @Volatile private var activeProfile: ProfileHelper.CachedProfile? = null+ @Volatile private var deactivationJob: Job? = null++ // Condition states+ @Volatile private var isCharging = false+ @Volatile private var isCarMode = false++ // Speed rolling average buffer+ private val speedBuffer = ArrayDeque<Float>()+ private val speedLock = Any()++ // Last known location for trip event logging+ @Volatile private var lastLocation: Location? = null++ fun onChargingStateChanged(charging: Boolean) {+ isCharging = charging+ evaluate()+ }++ fun onCarModeStateChanged(connected: Boolean) {+ isCarMode = connected+ evaluate()+ }++ fun onLocationUpdate(location: Location) {+ lastLocation = location++ if (location.hasSpeed()) {+ synchronized(speedLock) {+ if (speedBuffer.size >= SPEED_BUFFER_SIZE) {+ speedBuffer.removeFirst()+ }+ speedBuffer.addLast(location.speed)+ }+ }+ evaluate()+ }++ fun invalidateProfiles() {+ profileHelper.invalidateCache()+ }++ fun getActiveProfileName(): String? = activeProfile?.name++ /**+ * Re-evaluates all enabled profiles against current conditions.+ * Must handle concurrent calls from location updates, broadcasts, and service actions.+ */+ @Synchronized+ private fun evaluate() {+ val profiles = profileHelper.getEnabledProfiles()+ if (profiles.isEmpty()) {+ if (activeProfile != null) {+ scheduleDeactivation(activeProfile!!)+ }+ return+ }++ // Find highest-priority matching profile (list already sorted by priority DESC)+ val matchingProfile = profiles.firstOrNull { matchesCondition(it) }++ when {+ // A profile matches — activate it (or keep if already active)+ matchingProfile != null -> {+ if (activeProfile?.id == matchingProfile.id) {+ // Same profile still matches — cancel any pending deactivation+ cancelDeactivation()+ return+ }++ // Different profile or new activation+ cancelDeactivation()+ activateProfile(matchingProfile)+ }++ // No profile matches — schedule deactivation if one was active+ activeProfile != null -> {+ scheduleDeactivation(activeProfile!!)+ }+ }+ }++ private fun matchesCondition(profile: ProfileHelper.CachedProfile): Boolean {+ return when (profile.conditionType) {+ "charging" -> isCharging+ "android_auto" -> isCarMode+ "speed_above" -> {+ val avgSpeed = getAverageSpeed()+ val threshold = profile.speedThreshold+ avgSpeed != null && threshold != null && avgSpeed > threshold+ }+ "speed_below" -> {+ val avgSpeed = getAverageSpeed()+ val threshold = profile.speedThreshold+ avgSpeed != null && threshold != null && avgSpeed < threshold+ }+ else -> false+ }+ }++ private fun getAverageSpeed(): Float? {+ synchronized(speedLock) {+ if (speedBuffer.isEmpty()) return null+ return speedBuffer.average().toFloat()+ }+ }++ private fun activateProfile(profile: ProfileHelper.CachedProfile) {+ activeProfile = profile++ // Log trip event+ val loc = lastLocation+ profileHelper.logTripEvent(+ profileId = profile.id,+ profileName = profile.name,+ eventType = "activated",+ latitude = loc?.latitude,+ longitude = loc?.longitude,+ timestamp = System.currentTimeMillis() / 1000+ )++ if (BuildConfig.DEBUG) {+ Log.i(TAG, "Activated profile: ${profile.name} (interval=${profile.intervalMs}ms, sync=${profile.syncIntervalSeconds}s)")+ }++ // Notify JS+ LocationServiceModule.sendProfileSwitchEvent(profile.name, profile.id)++ // Apply config+ onConfigSwitch(+ profile.intervalMs,+ profile.minUpdateDistance,+ profile.syncIntervalSeconds,+ profile.name,+ profile.id+ )+ }++ private fun scheduleDeactivation(profile: ProfileHelper.CachedProfile) {+ if (deactivationJob?.isActive == true) return // already scheduled++ deactivationJob = scope.launch {+ delay(profile.deactivationDelaySeconds * 1000L)+ deactivateToDefault()+ }++ if (BuildConfig.DEBUG) {+ Log.d(TAG, "Scheduled deactivation of '${profile.name}' in ${profile.deactivationDelaySeconds}s")+ }+ }++ private fun cancelDeactivation() {+ deactivationJob?.cancel()+ deactivationJob = null+ }++ @Synchronized+ private fun deactivateToDefault() {+ val previousProfile = activeProfile ?: return+ activeProfile = null+ deactivationJob = null++ // Log trip event+ val loc = lastLocation+ profileHelper.logTripEvent(+ profileId = previousProfile.id,+ profileName = previousProfile.name,+ eventType = "deactivated",+ latitude = loc?.latitude,+ longitude = loc?.longitude,+ timestamp = System.currentTimeMillis() / 1000+ )++ if (BuildConfig.DEBUG) {+ Log.i(TAG, "Deactivated profile: ${previousProfile.name} — reverting to defaults")+ }++ // Notify JS+ LocationServiceModule.sendProfileSwitchEvent(null, null)++ // Revert to default config+ onConfigSwitch(defaultInterval, defaultDistance, defaultSyncInterval, null, null)+ }+}diff --git a/apps/mobile/src/screens/ProfileEditorScreen.tsx b/apps/mobile/src/screens/ProfileEditorScreen.tsxnew file mode 100644index 00000000..019811c4--- /dev/null+++ b/apps/mobile/src/screens/ProfileEditorScreen.tsx@@ -0,0 +1,429 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React, { useState, useEffect, useCallback } from "react"+import { View, Text, StyleSheet, ScrollView, TextInput, TouchableOpacity } from "react-native"+import { useTheme } from "../hooks/useTheme"+import { ProfileService } from "../services/ProfileService"+import { showAlert } from "../services/modalService"+import { TrackingProfile, ProfileConditionType } from "../types/global"+import { fonts } from "../styles/typography"+import { Container, SectionTitle, Card, Divider } from "../components"+import { Zap, Car, ArrowUp, ArrowDown, Check } from "lucide-react-native"+import { logger } from "../utils/logger"++const CONDITION_OPTIONS: {+ type: ProfileConditionType+ label: string+ icon: any+ description: string+}[] = [+ { type: "charging", label: "Charging", icon: Zap, description: "Phone is plugged in" },+ { type: "android_auto", label: "Car Mode", icon: Car, description: "Android Auto connected" },+ { type: "speed_above", label: "Speed Above", icon: ArrowUp, description: "Moving faster than threshold" },+ { type: "speed_below", label: "Speed Below", icon: ArrowDown, description: "Moving slower than threshold" }+]++const SYNC_OPTIONS = [+ { label: "Instant", value: 0 },+ { label: "1 min", value: 60 },+ { label: "5 min", value: 300 },+ { label: "15 min", value: 900 }+]++const DEFAULT_PROFILE: Omit<TrackingProfile, "id" | "createdAt"> = {+ name: "",+ interval: 5,+ distance: 0,+ syncInterval: 0,+ priority: 10,+ condition: { type: "charging" },+ deactivationDelay: 60,+ enabled: true+}++export function ProfileEditorScreen({ navigation, route }: any) {+ const { colors } = useTheme()+ const profileId = route?.params?.profileId as number | undefined+ const isEditing = !!profileId++ const [profile, setProfile] = useState<Omit<TrackingProfile, "id" | "createdAt">>(DEFAULT_PROFILE)+ const [speedKmh, setSpeedKmh] = useState("30")+ const [saving, setSaving] = useState(false)++ // String representations for numeric inputs+ const [intervalStr, setIntervalStr] = useState("5")+ const [distanceStr, setDistanceStr] = useState("0")+ const [priorityStr, setPriorityStr] = useState("10")+ const [delayStr, setDelayStr] = useState("60")++ useEffect(() => {+ if (!profileId) return++ ProfileService.getProfiles().then((profiles) => {+ const existing = profiles.find((p) => p.id === profileId)+ if (existing) {+ setProfile({+ name: existing.name,+ interval: existing.interval,+ distance: existing.distance,+ syncInterval: existing.syncInterval,+ priority: existing.priority,+ condition: existing.condition,+ deactivationDelay: existing.deactivationDelay,+ enabled: existing.enabled+ })+ setIntervalStr(String(existing.interval))+ setDistanceStr(String(existing.distance))+ setPriorityStr(String(existing.priority))+ setDelayStr(String(existing.deactivationDelay))+ if (existing.condition.speedThreshold) {+ setSpeedKmh((existing.condition.speedThreshold * 3.6).toFixed(0))+ }+ }+ })+ }, [profileId])++ const handleNumericChange = useCallback(+ (setter: (v: string) => void, field: keyof typeof profile, value: string, min = 0) => {+ setter(value)+ const num = Number(value)+ if (!isNaN(num) && num >= min) {+ setProfile((prev) => ({ ...prev, [field]: num }))+ }+ },+ []+ )++ const setConditionType = useCallback(+ (type: ProfileConditionType) => {+ const isSpeed = type === "speed_above" || type === "speed_below"+ setProfile((prev) => ({+ ...prev,+ condition: {+ type,+ ...(isSpeed ? { speedThreshold: Number(speedKmh) / 3.6 } : {})+ }+ }))+ },+ [speedKmh]+ )++ const handleSpeedChange = useCallback((val: string) => {+ setSpeedKmh(val)+ const num = Number(val)+ if (!isNaN(num) && num > 0) {+ setProfile((prev) => ({+ ...prev,+ condition: { ...prev.condition, speedThreshold: num / 3.6 }+ }))+ }+ }, [])++ const handleSave = useCallback(async () => {+ if (!profile.name.trim()) {+ showAlert("Missing Name", "Please enter a profile name.", "warning")+ return+ }++ setSaving(true)+ try {+ if (isEditing && profileId) {+ await ProfileService.updateProfile({ id: profileId, ...profile })+ } else {+ await ProfileService.createProfile(profile)+ }+ navigation.goBack()+ } catch (err) {+ logger.error("[ProfileEditor] Save failed:", err)+ showAlert("Error", "Failed to save profile.", "error")+ } finally {+ setSaving(false)+ }+ }, [profile, isEditing, profileId, navigation])++ const isSpeed = profile.condition.type === "speed_above" || profile.condition.type === "speed_below"++ const inputStyle = [+ styles.numInput,+ { backgroundColor: colors.backgroundElevated, color: colors.text, borderColor: colors.border }+ ]++ return (+ <Container>+ <ScrollView+ contentContainerStyle={styles.scrollContent}+ keyboardShouldPersistTaps="handled"+ showsVerticalScrollIndicator={false}+ >+ <View style={styles.header}>+ <Text style={[styles.title, { color: colors.text }]}>{isEditing ? "Edit Profile" : "New Profile"}</Text>+ </View>++ {/* Name & Priority */}+ <SectionTitle>Profile</SectionTitle>+ <Card>+ <View style={styles.inputGroup}>+ <Text style={[styles.label, { color: colors.textSecondary }]}>Name</Text>+ <TextInput+ style={[+ styles.input,+ { backgroundColor: colors.background, color: colors.text, borderColor: colors.border }+ ]}+ placeholder="e.g. Driving, Cycling..."+ placeholderTextColor={colors.placeholder}+ value={profile.name}+ onChangeText={(val) => setProfile((prev) => ({ ...prev, name: val }))}+ />+ </View>++ <Divider />++ <View style={styles.settingRow}>+ <View style={styles.settingContent}>+ <Text style={[styles.settingLabel, { color: colors.text }]}>Priority</Text>+ <Text style={[styles.settingHint, { color: colors.textLight }]}>+ Higher number wins when multiple profiles match+ </Text>+ </View>+ <TextInput+ style={inputStyle}+ keyboardType="numeric"+ value={priorityStr}+ onChangeText={(val) => handleNumericChange(setPriorityStr, "priority", val, 0)}+ placeholder="10"+ placeholderTextColor={colors.placeholder}+ />+ </View>+ </Card>++ {/* Condition */}+ <SectionTitle style={styles.sectionGap}>Activation Condition</SectionTitle>+ <Card>+ <View style={styles.conditionGrid}>+ {CONDITION_OPTIONS.map((opt) => {+ const Icon = opt.icon+ const selected = profile.condition.type === opt.type+ return (+ <TouchableOpacity+ key={opt.type}+ style={[+ styles.conditionOption,+ {+ backgroundColor: selected ? colors.primary + "15" : colors.background,+ borderColor: selected ? colors.primary : colors.border+ }+ ]}+ onPress={() => setConditionType(opt.type)}+ activeOpacity={0.7}+ >+ <Icon size={20} color={selected ? colors.primary : colors.textSecondary} />+ <Text style={[styles.conditionLabel, { color: selected ? colors.primary : colors.text }]}>+ {opt.label}+ </Text>+ <Text style={[styles.conditionDesc, { color: colors.textLight }]}>{opt.description}</Text>+ </TouchableOpacity>+ )+ })}+ </View>++ {isSpeed && (+ <>+ <Divider />+ <View style={styles.inputGroup}>+ <Text style={[styles.label, { color: colors.textSecondary }]}>Speed Threshold (km/h)</Text>+ <TextInput+ style={[+ styles.input,+ { backgroundColor: colors.background, color: colors.text, borderColor: colors.border }+ ]}+ placeholder="30"+ placeholderTextColor={colors.placeholder}+ value={speedKmh}+ onChangeText={handleSpeedChange}+ keyboardType="numeric"+ />+ </View>+ </>+ )}+ </Card>++ {/* Tracking Settings */}+ <SectionTitle style={styles.sectionGap}>Tracking Settings</SectionTitle>+ <Card>+ <View style={styles.settingRow}>+ <View style={styles.settingContent}>+ <Text style={[styles.settingLabel, { color: colors.text }]}>Tracking Interval</Text>+ </View>+ <View style={styles.inputWithUnit}>+ <TextInput+ style={inputStyle}+ keyboardType="numeric"+ value={intervalStr}+ onChangeText={(val) => handleNumericChange(setIntervalStr, "interval", val, 1)}+ placeholder="5"+ placeholderTextColor={colors.placeholder}+ />+ <Text style={[styles.unit, { color: colors.textSecondary }]}>sec</Text>+ </View>+ </View>++ <Divider />++ <View style={styles.settingRow}>+ <View style={styles.settingContent}>+ <Text style={[styles.settingLabel, { color: colors.text }]}>Movement Threshold</Text>+ </View>+ <View style={styles.inputWithUnit}>+ <TextInput+ style={inputStyle}+ keyboardType="numeric"+ value={distanceStr}+ onChangeText={(val) => handleNumericChange(setDistanceStr, "distance", val, 0)}+ placeholder="0"+ placeholderTextColor={colors.placeholder}+ />+ <Text style={[styles.unit, { color: colors.textSecondary }]}>m</Text>+ </View>+ </View>++ <Divider />++ <Text style={[styles.label, { color: colors.textSecondary, marginBottom: 8 }]}>Sync Interval</Text>+ <View style={styles.syncGrid}>+ {SYNC_OPTIONS.map((opt) => {+ const selected = profile.syncInterval === opt.value+ return (+ <TouchableOpacity+ key={opt.value}+ style={[+ styles.syncOption,+ {+ backgroundColor: selected ? colors.primary + "15" : colors.background,+ borderColor: selected ? colors.primary : colors.border+ }+ ]}+ onPress={() => setProfile((prev) => ({ ...prev, syncInterval: opt.value }))}+ activeOpacity={0.7}+ >+ <Text style={[styles.syncLabel, { color: selected ? colors.primary : colors.text }]}>+ {opt.label}+ </Text>+ </TouchableOpacity>+ )+ })}+ </View>+ </Card>++ {/* Deactivation Delay */}+ <SectionTitle style={styles.sectionGap}>Deactivation</SectionTitle>+ <Card>+ <View style={styles.settingRow}>+ <View style={styles.settingContent}>+ <Text style={[styles.settingLabel, { color: colors.text }]}>Deactivation Delay</Text>+ <Text style={[styles.settingHint, { color: colors.textLight }]}>+ Wait before reverting to default settings after the condition stops matching. Prevents rapid switching.+ </Text>+ </View>+ <View style={styles.inputWithUnit}>+ <TextInput+ style={inputStyle}+ keyboardType="numeric"+ value={delayStr}+ onChangeText={(val) => handleNumericChange(setDelayStr, "deactivationDelay", val, 0)}+ placeholder="60"+ placeholderTextColor={colors.placeholder}+ />+ <Text style={[styles.unit, { color: colors.textSecondary }]}>sec</Text>+ </View>+ </View>+ </Card>++ {/* Save Button */}+ <TouchableOpacity+ style={[styles.saveBtn, { backgroundColor: colors.primary, opacity: saving ? 0.6 : 1 }]}+ onPress={handleSave}+ disabled={saving}+ activeOpacity={0.7}+ >+ <Check size={20} color={colors.textOnPrimary} />+ <Text style={[styles.saveBtnText, { color: colors.textOnPrimary }]}>+ {saving ? "Saving..." : isEditing ? "Save Changes" : "Create Profile"}+ </Text>+ </TouchableOpacity>+ </ScrollView>+ </Container>+ )+}++const styles = StyleSheet.create({+ scrollContent: { paddingHorizontal: 16, paddingTop: 16, paddingBottom: 40 },+ header: { marginBottom: 20 },+ title: { fontSize: 28, ...fonts.bold, letterSpacing: -0.5 },+ inputGroup: { marginBottom: 4 },+ label: {+ fontSize: 12,+ ...fonts.semiBold,+ marginBottom: 6,+ textTransform: "uppercase",+ letterSpacing: 0.5+ },+ input: { padding: 14, borderWidth: 1.5, borderRadius: 10, fontSize: 15, ...fonts.regular },+ numInput: {+ borderWidth: 1,+ padding: 10,+ borderRadius: 10,+ fontSize: 15,+ textAlign: "center",+ width: 64,+ ...fonts.regular+ },+ inputWithUnit: { flexDirection: "row", alignItems: "center", gap: 6 },+ unit: { fontSize: 14, ...fonts.medium, minWidth: 28 },+ settingRow: {+ flexDirection: "row",+ justifyContent: "space-between",+ alignItems: "center",+ paddingVertical: 4+ },+ settingContent: { flex: 1, marginRight: 16 },+ settingLabel: { fontSize: 15, ...fonts.semiBold, marginBottom: 2 },+ settingHint: { fontSize: 12, ...fonts.regular, lineHeight: 16 },+ conditionGrid: {+ flexDirection: "row",+ flexWrap: "wrap",+ gap: 10+ },+ conditionOption: {+ width: "47%",+ padding: 12,+ borderRadius: 10,+ borderWidth: 1.5,+ alignItems: "center",+ gap: 4+ },+ conditionLabel: { fontSize: 13, ...fonts.semiBold },+ conditionDesc: { fontSize: 11, ...fonts.regular, textAlign: "center" },+ syncGrid: { flexDirection: "row", gap: 8 },+ syncOption: {+ flex: 1,+ padding: 12,+ borderRadius: 10,+ borderWidth: 1.5,+ alignItems: "center"+ },+ syncLabel: { fontSize: 13, ...fonts.semiBold },+ saveBtn: {+ flexDirection: "row",+ alignItems: "center",+ justifyContent: "center",+ gap: 8,+ padding: 16,+ borderRadius: 12,+ marginTop: 16+ },+ saveBtnText: { fontSize: 16, ...fonts.semiBold },+ sectionGap: { marginTop: 24 }+})diff --git a/apps/mobile/src/screens/SettingsScreen.tsx b/apps/mobile/src/screens/SettingsScreen.tsxindex 524e86b1..315bcc56 100644--- a/apps/mobile/src/screens/SettingsScreen.tsx+++ b/apps/mobile/src/screens/SettingsScreen.tsx@@ -147,6 +147,22 @@ export function SettingsScreen({ navigation }: ScreenProps) {<View style={styles.section}><SectionTitle>Advanced</SectionTitle><Card>+ <TouchableOpacity+ style={styles.linkRow}+ onPress={() => navigation.navigate("Tracking Profiles")}+ activeOpacity={0.6}+ >+ <View style={styles.linkContent}>+ <Text style={[styles.linkLabel, { color: colors.text }]}>Tracking Profiles</Text>+ <Text style={[styles.linkSub, { color: colors.textSecondary }]}>+ Auto-switch GPS settings based on conditions+ </Text>+ </View>+ <ChevronRight size={20} color={colors.textLight} />+ </TouchableOpacity>++ <Divider />+<TouchableOpacitystyle={styles.linkRow}onPress={() => navigation.navigate("Data Management")}diff --git a/apps/mobile/src/screens/TrackingProfilesScreen.tsx b/apps/mobile/src/screens/TrackingProfilesScreen.tsxnew file mode 100644index 00000000..99737905--- /dev/null+++ b/apps/mobile/src/screens/TrackingProfilesScreen.tsx@@ -0,0 +1,262 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React, { useState, useEffect, useCallback } from "react"+import { View, Text, StyleSheet, FlatList, Switch, TouchableOpacity, DeviceEventEmitter } from "react-native"+import { useTheme } from "../hooks/useTheme"+import { ProfileService } from "../services/ProfileService"+import { showAlert, showConfirm } from "../services/modalService"+import { TrackingProfile, ScreenProps } from "../types/global"+import { fonts } from "../styles/typography"+import { Container, SectionTitle, Card } from "../components"+import { Plus, X, Zap, Car, ArrowUp, ArrowDown } from "lucide-react-native"+import { logger } from "../utils/logger"++const CONDITION_LABELS: Record<string, string> = {+ charging: "When charging",+ android_auto: "Android Auto / Car mode",+ speed_above: "Speed above",+ speed_below: "Speed below"+}++const CONDITION_ICONS: Record<string, any> = {+ charging: Zap,+ android_auto: Car,+ speed_above: ArrowUp,+ speed_below: ArrowDown+}++function formatCondition(profile: TrackingProfile): string {+ const label = CONDITION_LABELS[profile.condition.type] || profile.condition.type+ if (profile.condition.type === "speed_above" || profile.condition.type === "speed_below") {+ const kmh = ((profile.condition.speedThreshold ?? 0) * 3.6).toFixed(0)+ return `${label} ${kmh} km/h`+ }+ return label+}++function formatSettings(profile: TrackingProfile): string {+ const parts = [`${profile.interval}s interval`]+ if (profile.distance > 0) parts.push(`${profile.distance}m threshold`)+ parts.push(profile.syncInterval === 0 ? "instant sync" : `${profile.syncInterval}s sync`)+ return parts.join(" \u2022 ")+}++export function TrackingProfilesScreen({ navigation }: ScreenProps) {+ const { colors } = useTheme()+ const [profiles, setProfiles] = useState<TrackingProfile[]>([])+ const [activeProfileName, setActiveProfileName] = useState<string | null>(null)++ const loadProfiles = useCallback(async () => {+ try {+ const data = await ProfileService.getProfiles()+ setProfiles(data)+ } catch (err) {+ logger.error("[TrackingProfilesScreen] Failed to load profiles:", err)+ }+ }, [])++ useEffect(() => {+ loadProfiles()+ }, [loadProfiles])++ // Listen for profile switch events from the native service+ useEffect(() => {+ const listener = DeviceEventEmitter.addListener("onProfileSwitch", (event) => {+ setActiveProfileName(event.profileName ?? null)+ })+ return () => listener.remove()+ }, [])++ // Reload when returning from editor+ useEffect(() => {+ const unsubscribe = navigation.addListener("focus", () => {+ loadProfiles()+ })+ return unsubscribe+ }, [navigation, loadProfiles])++ const toggleEnabled = useCallback(+ async (id: number, value: boolean) => {+ try {+ await ProfileService.updateProfile({ id, enabled: value })+ await loadProfiles()+ } catch {+ showAlert("Error", "Failed to update profile.", "error")+ }+ },+ [loadProfiles]+ )++ const handleDelete = useCallback(+ async (item: TrackingProfile) => {+ const confirmed = await showConfirm({+ title: "Delete Profile",+ message: `Delete "${item.name}"?`,+ confirmText: "Delete",+ destructive: true+ })++ if (!confirmed) return++ try {+ await ProfileService.deleteProfile(item.id!)+ await loadProfiles()+ } catch {+ showAlert("Error", "Failed to delete profile.", "error")+ }+ },+ [loadProfiles]+ )++ const renderItem = useCallback(+ ({ item }: { item: TrackingProfile }) => {+ const ConditionIcon = CONDITION_ICONS[item.condition.type] || Zap+ const isActive = activeProfileName === item.name++ return (+ <Card style={[styles.card, isActive && { borderColor: colors.primary, borderWidth: 2 }]}>+ <TouchableOpacity+ style={styles.row}+ onPress={() => navigation.navigate("Profile Editor", { profileId: item.id })}+ activeOpacity={0.7}+ >+ <View style={[styles.iconWrap, { backgroundColor: colors.primary + "15" }]}>+ <ConditionIcon size={18} color={colors.primary} />+ </View>++ <View style={styles.info}>+ <View style={styles.nameRow}>+ <Text style={[styles.name, { color: colors.text }]}>{item.name}</Text>+ {isActive && (+ <View style={[styles.activeBadge, { backgroundColor: colors.success + "20" }]}>+ <Text style={[styles.activeBadgeText, { color: colors.success }]}>Active</Text>+ </View>+ )}+ <View style={[styles.priorityBadge, { backgroundColor: colors.border }]}>+ <Text style={[styles.priorityText, { color: colors.textSecondary }]}>P{item.priority}</Text>+ </View>+ </View>+ <Text style={[styles.condition, { color: colors.textSecondary }]}>{formatCondition(item)}</Text>+ <Text style={[styles.settings, { color: colors.textLight }]}>{formatSettings(item)}</Text>+ </View>++ <View style={styles.actions}>+ <Switch+ value={item.enabled}+ onValueChange={(val) => toggleEnabled(item.id!, val)}+ trackColor={{ false: colors.border, true: colors.primary + "80" }}+ thumbColor={item.enabled ? colors.primary : colors.border}+ />++ <TouchableOpacity+ onPress={() => handleDelete(item)}+ style={[styles.deleteBtn, { backgroundColor: colors.error + "15" }]}+ activeOpacity={0.7}+ >+ <X size={16} color={colors.error} />+ </TouchableOpacity>+ </View>+ </TouchableOpacity>+ </Card>+ )+ },+ [colors, activeProfileName, toggleEnabled, handleDelete, navigation]+ )++ return (+ <Container>+ <FlatList+ data={profiles}+ keyExtractor={(item) => item.id!.toString()}+ contentContainerStyle={styles.list}+ showsVerticalScrollIndicator={false}+ ListHeaderComponent={+ <>+ <View style={styles.header}>+ <Text style={[styles.title, { color: colors.text }]}>Tracking Profiles</Text>+ <Text style={[styles.subtitle, { color: colors.textSecondary }]}>+ Auto-switch GPS settings based on charging, Android Auto, or speed+ </Text>+ </View>++ <TouchableOpacity+ style={[styles.createBtn, { backgroundColor: colors.primary }]}+ onPress={() => navigation.navigate("Profile Editor", {})}+ activeOpacity={0.7}+ >+ <Plus size={20} color={colors.textOnPrimary} />+ <Text style={[styles.createBtnText, { color: colors.textOnPrimary }]}>Create Profile</Text>+ </TouchableOpacity>++ {profiles.length > 0 && <SectionTitle>Profiles ({profiles.length})</SectionTitle>}+ </>+ }+ ListEmptyComponent={+ <View style={styles.empty}>+ <Text style={[styles.emptyText, { color: colors.textSecondary }]}>No profiles yet</Text>+ <Text style={[styles.emptyHint, { color: colors.textLight }]}>+ Create a profile to automatically switch tracking settings when charging, connected to Android Auto, or+ based on speed+ </Text>+ </View>+ }+ renderItem={renderItem}+ />+ </Container>+ )+}++const styles = StyleSheet.create({+ list: { padding: 16, paddingBottom: 40 },+ header: { marginBottom: 20 },+ title: { fontSize: 28, ...fonts.bold, letterSpacing: -0.5, marginBottom: 6 },+ subtitle: { fontSize: 14, ...fonts.regular, lineHeight: 20 },+ createBtn: {+ flexDirection: "row",+ alignItems: "center",+ justifyContent: "center",+ gap: 8,+ padding: 16,+ borderRadius: 12,+ marginBottom: 24+ },+ createBtnText: { fontSize: 15, ...fonts.semiBold },+ card: { marginBottom: 12, padding: 14 },+ row: { flexDirection: "row", alignItems: "center" },+ iconWrap: {+ width: 36,+ height: 36,+ borderRadius: 10,+ alignItems: "center",+ justifyContent: "center",+ marginRight: 12+ },+ info: { flex: 1, marginRight: 12 },+ nameRow: { flexDirection: "row", alignItems: "center", gap: 8, marginBottom: 2 },+ name: { fontSize: 15, ...fonts.semiBold },+ activeBadge: { paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4 },+ activeBadgeText: { fontSize: 10, ...fonts.semiBold, textTransform: "uppercase" },+ priorityBadge: { paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4 },+ priorityText: { fontSize: 10, ...fonts.semiBold },+ condition: { fontSize: 13, ...fonts.medium, marginBottom: 2 },+ settings: { fontSize: 11, ...fonts.regular },+ actions: { alignItems: "center", gap: 8 },+ deleteBtn: {+ width: 32,+ height: 32,+ borderRadius: 16,+ alignItems: "center",+ justifyContent: "center"+ },+ empty: { alignItems: "center", paddingVertical: 40 },+ emptyText: { fontSize: 15, ...fonts.semiBold, marginBottom: 6 },+ emptyHint: {+ fontSize: 13,+ textAlign: "center",+ maxWidth: 280,+ lineHeight: 18+ }+})diff --git a/apps/mobile/src/screens/index.ts b/apps/mobile/src/screens/index.tsindex c7c50e7b..bc591a12 100644--- a/apps/mobile/src/screens/index.ts+++ b/apps/mobile/src/screens/index.ts@@ -11,4 +11,6 @@ export { ExportDataScreen } from "./ExportDataScreen"export { GeofenceScreen } from "./GeofenceScreen"export { LocationHistoryScreen } from "./LocationInspectorScreen"export { SettingsScreen } from "./SettingsScreen"+export { TrackingProfilesScreen } from "./TrackingProfilesScreen"+export { ProfileEditorScreen } from "./ProfileEditorScreen"export { AboutScreen } from "./AboutScreen"diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.tsindex 8be250ab..b7ee211d 100644--- a/apps/mobile/src/services/NativeLocationService.ts+++ b/apps/mobile/src/services/NativeLocationService.ts@@ -4,7 +4,7 @@*/import { NativeModules } from "react-native"-import { AuthConfig, DatabaseStats, Geofence, Settings } from "../types/global"+import { AuthConfig, DatabaseStats, Geofence, Settings, TrackingProfile, TripEvent } from "../types/global"import { logger } from "../utils/logger"const { LocationServiceModule, BuildConfigModule } = NativeModules@@ -321,6 +321,108 @@ class NativeLocationService {}}+ // ============================================================================+ // TRACKING PROFILES+ // ============================================================================++ /**+ * Fetches all tracking profiles+ */+ static async getProfiles(): Promise<TrackingProfile[]> {+ this.ensureModule()+ const raw = await this.safeExecute(() => LocationServiceModule.getProfiles(), [], "getProfiles failed")+ return raw.map((p: any) => ({+ id: p.id,+ name: p.name,+ interval: p.intervalMs / 1000, // ms → seconds for UI+ distance: p.minUpdateDistance,+ syncInterval: p.syncIntervalSeconds,+ priority: p.priority,+ condition: {+ type: p.conditionType,+ ...(p.speedThreshold != null ? { speedThreshold: p.speedThreshold } : {})+ },+ deactivationDelay: p.deactivationDelaySeconds,+ enabled: p.enabled,+ createdAt: p.createdAt+ }))+ }++ /**+ * Creates a new tracking profile+ * @returns Profile ID+ */+ static async createProfile(profile: Omit<TrackingProfile, "id" | "createdAt">): Promise<number> {+ this.ensureModule()+ logger.debug("[NativeLocationService] Creating profile:", profile.name)+ return LocationServiceModule.createProfile({+ name: profile.name,+ intervalMs: profile.interval * 1000, // seconds → ms+ minUpdateDistance: profile.distance,+ syncIntervalSeconds: profile.syncInterval,+ priority: profile.priority,+ conditionType: profile.condition.type,+ speedThreshold: profile.condition.speedThreshold ?? null,+ deactivationDelaySeconds: profile.deactivationDelay+ })+ }++ /**+ * Updates an existing tracking profile (partial updates supported)+ */+ static async updateProfile(update: Partial<TrackingProfile> & { id: number }): Promise<boolean> {+ this.ensureModule()+ logger.debug("[NativeLocationService] Updating profile:", update.id)++ const config: any = { id: update.id }+ if (update.name !== undefined) config.name = update.name+ if (update.interval !== undefined) config.intervalMs = update.interval * 1000+ if (update.distance !== undefined) config.minUpdateDistance = update.distance+ if (update.syncInterval !== undefined) config.syncIntervalSeconds = update.syncInterval+ if (update.priority !== undefined) config.priority = update.priority+ if (update.condition !== undefined) {+ config.conditionType = update.condition.type+ config.speedThreshold = update.condition.speedThreshold ?? null+ }+ if (update.deactivationDelay !== undefined) config.deactivationDelaySeconds = update.deactivationDelay+ if (update.enabled !== undefined) config.enabled = update.enabled++ return LocationServiceModule.updateProfile(config)+ }++ /**+ * Deletes a tracking profile+ */+ static async deleteProfile(id: number): Promise<boolean> {+ this.ensureModule()+ logger.debug("[NativeLocationService] Deleting profile:", id)+ return LocationServiceModule.deleteProfile(id)+ }++ /**+ * Triggers profile re-evaluation in the foreground service+ */+ static async recheckProfiles(): Promise<void> {+ this.ensureModule()+ try {+ await LocationServiceModule.recheckProfiles()+ } catch (error) {+ logger.error("[NativeLocationService] Profile recheck failed:", error)+ }+ }++ /**+ * Fetches trip events within a date range+ */+ static async getTripEvents(startTimestamp: number, endTimestamp: number): Promise<TripEvent[]> {+ this.ensureModule()+ return this.safeExecute(+ () => LocationServiceModule.getTripEvents(startTimestamp, endTimestamp),+ [],+ "getTripEvents failed"+ )+ }+// ============================================================================// SETTINGS OPERATIONS// ============================================================================diff --git a/apps/mobile/src/services/ProfileService.ts b/apps/mobile/src/services/ProfileService.tsnew file mode 100644index 00000000..adcf0cba--- /dev/null+++ b/apps/mobile/src/services/ProfileService.ts@@ -0,0 +1,30 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import NativeLocationService from "./NativeLocationService"+import { TrackingProfile, TripEvent } from "../types/global"++/**+ * Service for managing tracking profiles.+ * Thin wrapper over NativeLocationService profile methods.+ */+export const ProfileService = {+ getProfiles: (): Promise<TrackingProfile[]> => NativeLocationService.getProfiles(),++ createProfile: (profile: Omit<TrackingProfile, "id" | "createdAt">): Promise<number> =>+ NativeLocationService.createProfile(profile),++ updateProfile: (update: Partial<TrackingProfile> & { id: number }): Promise<boolean> =>+ NativeLocationService.updateProfile(update),++ deleteProfile: (id: number): Promise<boolean> => NativeLocationService.deleteProfile(id),++ recheckProfiles: (): Promise<void> => NativeLocationService.recheckProfiles(),++ getTripEvents: (startTimestamp: number, endTimestamp: number): Promise<TripEvent[]> =>+ NativeLocationService.getTripEvents(startTimestamp, endTimestamp)+}++export default ProfileServicediff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.tsindex c9e7f7b7..97cc8584 100644--- a/apps/mobile/src/types/global.ts+++ b/apps/mobile/src/types/global.ts@@ -318,6 +318,54 @@ export const DEFAULT_AUTH_CONFIG: AuthConfig = {customHeaders: {}}+// ============================================================================+// TRACKING PROFILES+// ============================================================================++export type ProfileConditionType = "charging" | "android_auto" | "speed_above" | "speed_below"++export interface ProfileCondition {+ type: ProfileConditionType+ /** Speed threshold in m/s (only for speed_above / speed_below conditions) */+ speedThreshold?: number+}++export interface TrackingProfile {+ id?: number+ name: string+ /** GPS interval in seconds */+ interval: number+ /** Movement threshold in meters */+ distance: number+ /** Sync interval in seconds */+ syncInterval: number+ /** Higher priority wins when multiple profiles match */+ priority: number+ /** The condition that activates this profile */+ condition: ProfileCondition+ /** Seconds to wait before deactivating after condition stops matching */+ deactivationDelay: number+ /** Whether this profile is enabled */+ enabled: boolean+ createdAt?: number+}++export interface ActiveProfileInfo {+ profileId: number+ profileName: string+ activatedAt: number+}++export interface TripEvent {+ id: number+ profileId: number | null+ profileName: string+ eventType: "activated" | "deactivated"+ latitude: number | null+ longitude: number | null+ timestamp: number+}+// ============================================================================// DATABASE// ============================================================================