Skip to content

Colota - Android GPS Location tracker

first commit

Max Dietrich97ca3535bcc5
diff --git a/android/app/build.gradle b/android/app/build.gradle
index 7e3ffff5..5be7da0f 100644
--- a/android/app/build.gradle
+++ b/android/app/build.gradle
@@ -83,8 +83,8 @@ android {
applicationId "com.Colota"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
- versionCode 4
- versionName "1.1.0"
+ versionCode 6
+ versionName "1.3.0"
// Expose build config to the module
buildConfigField "int", "MIN_SDK_VERSION", "${rootProject.ext.minSdkVersion}"
diff --git a/android/app/src/main/java/com/locata/LocationBootReceiver.kt b/android/app/src/main/java/com/locata/LocationBootReceiver.kt
index 148553ab..66cd8415 100644
--- a/android/app/src/main/java/com/locata/LocationBootReceiver.kt
+++ b/android/app/src/main/java/com/locata/LocationBootReceiver.kt
@@ -10,18 +10,10 @@ import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.launch
+import kotlinx.coroutines.*
/**
* Receiver responsible for restarting the location tracking service after device reboot.
- *
- * Optimized for:
- * - Fast execution (doesn't block boot process)
- * - Proper async database access
- * - Multiple boot action support
- * - Better error handling
*/
class LocationBootReceiver : BroadcastReceiver() {
@@ -34,6 +26,9 @@ class LocationBootReceiver : BroadcastReceiver() {
Intent.ACTION_LOCKED_BOOT_COMPLETED,
"android.intent.action.QUICKBOOT_POWERON"
)
+
+ private const val MAX_DB_RETRIES = 3
+ private const val RETRY_DELAY_MS = 1000L
}
override fun onReceive(context: Context, intent: Intent) {
@@ -48,73 +43,79 @@ class LocationBootReceiver : BroadcastReceiver() {
// Run database check on background thread
CoroutineScope(Dispatchers.IO).launch {
try {
- handleBootCompleted(context, action)
+ handleBootCompleted(context.applicationContext, action)
} catch (e: Exception) {
Log.e(TAG, "Error handling boot", e)
} finally {
- // Must call finish() when done
+ // CRITICAL: Always call finish()
pendingResult.finish()
}
}
}
- private fun handleBootCompleted(context: Context, action: String) {
- try {
- val dbHelper = LocationDatabaseHelper.getInstance(context.applicationContext)
- val isEnabled = dbHelper.getSetting("tracking_enabled", "false") == "true"
-
- if (isEnabled) {
+ /**
+ * Waits for database to be ready with retry logic.
+ * Database might not be immediately available after boot.
+ */
+ private suspend fun waitForDatabaseReady(dbHelper: LocationDatabaseHelper): Boolean {
+ repeat(MAX_DB_RETRIES) { attempt ->
+ try {
+ // Test database access
+ dbHelper.getSetting("tracking_enabled")
+ return true
+ } catch (e: Exception) {
if (BuildConfig.DEBUG) {
- Log.d(TAG, "Boot detected ($action). Restarting service...")
- }
-
- val serviceIntent = Intent(context, LocationForegroundService::class.java).apply {
- // Pass all settings to service
- val settings = dbHelper.getAllSettings()
-
- settings["interval"]?.toLongOrNull()?.let {
- putExtra("interval", it)
- }
- settings["minUpdateDistance"]?.toFloatOrNull()?.let {
- putExtra("minUpdateDistance", it)
- }
- settings["endpoint"]?.let {
- putExtra("endpoint", it)
- }
- settings["syncInterval"]?.toIntOrNull()?.let {
- putExtra("syncInterval", it)
- }
- settings["accuracyThreshold"]?.toFloatOrNull()?.let {
- putExtra("accuracyThreshold", it)
- }
- settings["filterInaccurateLocations"]?.toBooleanStrictOrNull()?.let {
- putExtra("filterInaccurateLocations", it)
- }
- settings["maxRetries"]?.toIntOrNull()?.let {
- putExtra("maxRetries", it)
- }
- settings["retryInterval"]?.toIntOrNull()?.let {
- putExtra("retryInterval", it)
- }
- settings["isOfflineMode"]?.toBooleanStrictOrNull()?.let {
- putExtra("isOfflineMode", it)
- }
- settings["fieldMap"]?.let {
- putExtra("fieldMap", it)
- }
+ Log.d(TAG, "DB not ready, attempt ${attempt + 1}/$MAX_DB_RETRIES")
}
-
- // Start service based on Android version
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- context.startForegroundService(serviceIntent)
- } else {
- context.startService(serviceIntent)
+ if (attempt < MAX_DB_RETRIES - 1) {
+ delay(RETRY_DELAY_MS)
}
- } else {
+ }
+ }
+ return false
+ }
+
+ private suspend fun handleBootCompleted(context: Context, action: String) {
+ try {
+ val dbHelper = LocationDatabaseHelper.getInstance(context)
+
+ // Wait for database to be ready
+ if (!waitForDatabaseReady(dbHelper)) {
+ Log.e(TAG, "Database not ready after $MAX_DB_RETRIES attempts")
+ return
+ }
+
+ val isEnabled = dbHelper.getSetting("tracking_enabled", "false") == "true"
+
+ if (!isEnabled) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Boot detected but tracking disabled")
}
+ return
+ }
+
+ if (BuildConfig.DEBUG) {
+ Log.d(TAG, "Boot detected ($action). Restarting service...")
+ }
+
+ // Load config using ServiceConfig (eliminates duplication)
+ val config = ServiceConfig.fromDatabase(dbHelper)
+
+ // Create service intent with config
+ val serviceIntent = Intent(context, LocationForegroundService::class.java)
+ config.toIntent(serviceIntent)
+
+ // Start service based on Android version
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ context.startForegroundService(serviceIntent)
+ } else {
+ context.startService(serviceIntent)
}
+
+ if (BuildConfig.DEBUG) {
+ Log.d(TAG, "Service start requested successfully")
+ }
+
} catch (e: SecurityException) {
Log.e(TAG, "Permission denied when starting service", e)
} catch (e: Exception) {
diff --git a/android/app/src/main/java/com/locata/LocationDatabaseHelper.kt b/android/app/src/main/java/com/locata/LocationDatabaseHelper.kt
index 5a126dce..21da8813 100644
--- a/android/app/src/main/java/com/locata/LocationDatabaseHelper.kt
+++ b/android/app/src/main/java/com/locata/LocationDatabaseHelper.kt
@@ -410,12 +410,12 @@ class LocationDatabaseHelper private constructor(context: Context) :
*/
@Synchronized
fun incrementRetryCount(queueId: Long, error: String? = null) {
- incrementRetryStmt?.let { stmt ->
- stmt.clearBindings()
- stmt.bindString(1, error ?: "")
- stmt.bindLong(2, queueId)
- stmt.executeUpdateDelete()
- }
+ val stmt = incrementRetryStmt ?: return // Exit if statement is null
+
+ stmt.clearBindings()
+ stmt.bindString(1, error ?: "")
+ stmt.bindLong(2, queueId)
+ stmt.executeUpdateDelete()
}
// ========================== STATS OPERATIONS ==========================
@@ -508,9 +508,10 @@ class LocationDatabaseHelper private constructor(context: Context) :
}
/**
- * Synchronous vacuum for backward compatibility.
- * Can block UI for seconds. Use vacuumAsync() instead.
- */
+ * Optimizes database by reclaiming unused space.
+ * WARNING: Can block for several seconds on large databases.
+ * Call from background thread only.
+ */
fun vacuum() {
writableDatabase.execSQL("VACUUM")
writableDatabase.execSQL("ANALYZE")
diff --git a/android/app/src/main/java/com/locata/LocationForegroundService.kt b/android/app/src/main/java/com/locata/LocationForegroundService.kt
index 2bd8166c..9ca77f4e 100644
--- a/android/app/src/main/java/com/locata/LocationForegroundService.kt
+++ b/android/app/src/main/java/com/locata/LocationForegroundService.kt
@@ -39,34 +39,30 @@ class LocationForegroundService : Service() {
// Notification throttling
private var lastNotificationTime: Long = 0
- private val NOTIFICATION_THROTTLE_MS = 5000L // Max 1 per 5 seconds
+ private val NOTIFICATION_THROTTLE_MS = 10000L // Max 1 per 5 seconds
// DB query caching
private var cachedQueuedCount: Int = 0
private var lastQueueCountCheck: Long = 0
- private val QUEUE_COUNT_CACHE_MS = 3000L
+ private val QUEUE_COUNT_CACHE_MS = 5000L
// Location caching
private var lastKnownLocation: android.location.Location? = null
+ private var lastNotificationCoords: Pair<Double, Double>? = null
// Battery check throttling
private var cachedBatteryLevel: Int = 100
private var cachedBatteryStatus: Int = 0
private var lastBatteryCheck: Long = 0
- private val BATTERY_CHECK_INTERVAL_MS = 30000L
+ private val BATTERY_CHECK_INTERVAL_MS = 60000L
- // --- Configuration (GPS settings) ---
- private var interval: Long = 0L
- private var minUpdateDistance: Float = 0f
- private var endpoint: String = ""
+ // Batch limit to prevent infinite syncing
+ private val MAX_BATCHES_PER_SYNC = 10 // Max 500 items per sync cycle
+
+ // --- Configuration (use ServiceConfig) ---
+ private lateinit var config: ServiceConfig
private var fieldMap: Map<String, String>? = null
- private var maxRetries: Int = 0
private var consecutiveFailures = 0
- private var syncIntervalSeconds: Int = -1
- private var retryIntervalSeconds: Int = 0
- private var filterInaccurateLocations: Boolean = false
- private var accuracyThreshold: Float = 0f
- private var isOfflineMode: Boolean = false
private val CHANNEL_ID = "location_service_channel"
private val NOTIFICATION_ID = 1
@@ -130,7 +126,6 @@ class LocationForegroundService : Service() {
Log.d(TAG, "Force exit from zone: $currentZoneName")
}
exitSilentZone()
-
// Immediately recheck with current location
lastKnownLocation?.let { recheckZoneWithLocation(it) }
}
@@ -141,9 +136,9 @@ class LocationForegroundService : Service() {
return START_STICKY
}
ACTION_MANUAL_FLUSH -> {
- if (endpoint.isNotBlank()) {
+ if (config.endpoint.isNotBlank()) {
serviceScope?.launch {
- syncQueue(endpoint)
+ syncQueue(config.endpoint)
}
}
return START_STICKY
@@ -157,13 +152,13 @@ class LocationForegroundService : Service() {
syncInitialized = false
setupLocationUpdates()
- if (syncIntervalSeconds > 0) {
+ if (config.syncIntervalSeconds > 0) {
startSyncJob()
}
}
- if (syncIntervalSeconds == 0 && endpoint.isNotBlank()) {
- syncQueue(endpoint)
+ if (config.syncIntervalSeconds == 0 && config.endpoint.isNotBlank()) {
+ syncQueue(config.endpoint)
}
}
}
@@ -200,20 +195,23 @@ class LocationForegroundService : Service() {
// Use cached battery status
val (batteryLevel, batteryStatus) = getCachedBatteryStatus()
- // Priority logic
- val priority = when {
- batteryLevel < 5 && batteryStatus == 1 -> {
- stopForegroundServiceWithReason("Battery critical")
- return
+ // Stop service if battery critical AND not charging
+ if (batteryLevel < 5 && batteryStatus == 1) {
+ if (BuildConfig.DEBUG) {
+ Log.d(TAG, "Battery critical ($batteryLevel%) and unplugged - stopping service")
}
- else -> Priority.PRIORITY_HIGH_ACCURACY
+ stopForegroundServiceWithReason("Battery critical")
+ return // Exit early - don't setup location updates
}
+ // Battery is OK or charging - use high accuracy
+ val priority = Priority.PRIORITY_HIGH_ACCURACY
+
// Request parameters
- val locationRequest = LocationRequest.Builder(priority, interval * 2)
- .setMinUpdateIntervalMillis(interval)
- .setMinUpdateDistanceMeters(minUpdateDistance)
- .setMaxUpdateDelayMillis(interval * 2)
+ val locationRequest = LocationRequest.Builder(priority, config.interval * 2)
+ .setMinUpdateIntervalMillis(config.interval)
+ .setMinUpdateDistanceMeters(config.minUpdateDistance)
+ .setMaxUpdateDelayMillis(config.interval * 2)
.build()
try {
@@ -226,8 +224,13 @@ class LocationForegroundService : Service() {
fusedLocationClient.lastLocation.addOnSuccessListener { location ->
location?.let {
lastKnownLocation = it
+
+ // Check if starting in a pause zone
locationUtils.getSilentZone(it)?.let { zoneName ->
enterSilentZone(GeofenceInfo(-1, zoneName))
+ } ?: run {
+ // Not in zone - show coordinates immediately
+ updateNotification(it.latitude, it.longitude, forceUpdate = true)
}
}
}
@@ -243,12 +246,16 @@ class LocationForegroundService : Service() {
}
private fun handleZoneRecheckAction() {
+ locationUtils.invalidateGeofenceCache()
+
val cachedLoc = lastKnownLocation
val now = System.currentTimeMillis()
+ // If we have a fresh location (less than 1 min old), recheck immediately
if (cachedLoc != null && (now - cachedLoc.time) < 60000) {
recheckZoneWithLocation(cachedLoc)
} else {
+ // Otherwise, request the last known location from the provider
fusedLocationClient.lastLocation.addOnSuccessListener { location ->
location?.let {
lastKnownLocation = it
@@ -277,26 +284,34 @@ class LocationForegroundService : Service() {
val zoneName = locationUtils.getSilentZone(location)
when {
- // Just entered a new zone or changed zones
+ // Just entered a pause zone or changed zones
zoneName != null && (!insideSilentZone || zoneName != currentZoneName) -> {
enterSilentZone(GeofenceInfo(-1, zoneName))
}
- // Just exited (zone was deleted or moved out)
+ // Just exited pause zone
zoneName == null && insideSilentZone -> {
exitSilentZone()
- updateNotification(location.latitude, location.longitude)
}
- // Still in the same zone
+ // Still in the same pause zone - update coords but keep paused status
zoneName != null && insideSilentZone && zoneName == currentZoneName -> {
- // Don't change state, just ensure notification shows current coords
- updateNotification(lat = location.latitude, lon = location.longitude)
+ updateNotification(
+ lat = location.latitude,
+ lon = location.longitude,
+ pausedInZone = true,
+ zoneName = currentZoneName,
+ forceUpdate = true
+ )
}
- // Standard movement (No zone) - make sure we show coords
+ // Standard movement (no zone) - show coords
else -> {
- updateNotification(location.latitude, location.longitude)
+ updateNotification(
+ location.latitude,
+ location.longitude,
+ forceUpdate = true
+ )
}
}
}
@@ -307,19 +322,30 @@ class LocationForegroundService : Service() {
private fun handleLocationUpdate(location: android.location.Location) {
// Early returns for filtering
- if (filterInaccurateLocations && location.accuracy > accuracyThreshold) {
+ if (config.filterInaccurateLocations && location.accuracy > config.accuracyThreshold) {
return
}
// Cache location
lastKnownLocation = location
- // Silent Zone Logic
+ // Silent Zone Logic - CHECK IF IT'S A PAUSE ZONE
val zoneName = locationUtils.getSilentZone(location)
+
when {
- zoneName != null && !insideSilentZone -> enterSilentZone(GeofenceInfo(-1, zoneName))
- zoneName == null && insideSilentZone -> exitSilentZone()
- zoneName != null && insideSilentZone -> return // Still in zone, skip
+ zoneName != null && !insideSilentZone -> {
+ // Entering a pause zone
+ enterSilentZone(GeofenceInfo(-1, zoneName))
+ return // Don't record location in pause zone
+ }
+ zoneName == null && insideSilentZone -> {
+ // Exiting pause zone
+ exitSilentZone()
+ }
+ zoneName != null && insideSilentZone -> {
+ // Still in pause zone, skip recording
+ return
+ }
}
// Use cached battery
@@ -337,11 +363,11 @@ class LocationForegroundService : Service() {
battery = battery,
battery_status = batteryStatus,
timestamp = timestampSec,
- endpoint = endpoint
+ endpoint = config.endpoint
)
// Send to React Native
- LocationServiceModule.sendLocationEvent(location)
+ LocationServiceModule.sendLocationEvent(location, battery, batteryStatus)
// Build payload once
val currentFieldMap = fieldMap ?: emptyMap()
@@ -355,31 +381,39 @@ class LocationForegroundService : Service() {
// Queue and optionally send (don't launch new coroutine if already in one)
serviceScope?.launch {
- queueAndSend(locationId, payload, endpoint)
+ queueAndSend(locationId, payload, config.endpoint)
}
// Update notification (throttled)
- updateNotificationThrottled(location.latitude, location.longitude)
+ updateNotification(location.latitude, location.longitude)
}
private fun enterSilentZone(zone: GeofenceInfo) {
insideSilentZone = true
currentZoneName = zone.name
- // Use last known location if available
+ // Always show paused status when entering a silent zone
lastKnownLocation?.let { loc ->
updateNotification(
lat = loc.latitude,
lon = loc.longitude,
- pausedInZone = true,
- zoneName = zone.name
+ pausedInZone = true,
+ zoneName = zone.name,
+ forceUpdate = true
)
} ?: run {
- // No location yet, show paused status only
- updateNotification(pausedInZone = true, zoneName = zone.name)
+ updateNotification(
+ pausedInZone = true,
+ zoneName = zone.name,
+ forceUpdate = true
+ )
}
LocationServiceModule.sendSilentZoneEvent(true, zone.name)
+
+ if (BuildConfig.DEBUG) {
+ Log.d(TAG, "Entered pause zone: ${zone.name}")
+ }
}
@@ -388,16 +422,19 @@ class LocationForegroundService : Service() {
val exited = currentZoneName
currentZoneName = null
- // Use last known location if available, otherwise show "Searching GPS"
+ // Show coordinates when exiting pause zone
lastKnownLocation?.let { loc ->
- updateNotification(loc.latitude, loc.longitude)
+ updateNotification(
+ loc.latitude,
+ loc.longitude,
+ forceUpdate = true // ← Force immediate update on zone exit
+ )
} ?: run {
- // If no location, show "Searching GPS..." instead of staying paused
- updateNotification()
+ updateNotification(forceUpdate = true)
}
LocationServiceModule.sendSilentZoneEvent(false, exited)
- if (BuildConfig.DEBUG) Log.d(TAG, "Exited zone: $exited")
+ if (BuildConfig.DEBUG) Log.d(TAG, "Exited pause zone: $exited")
}
// ========================================
@@ -434,28 +471,6 @@ class LocationForegroundService : Service() {
return cachedQueuedCount
}
- /**
- * Notification updates.
- */
- private fun updateNotificationThrottled(
- lat: Double? = null,
- lon: Double? = null,
- pausedInZone: Boolean = false,
- zoneName: String? = null
- ) {
- val now = System.currentTimeMillis()
-
- // Always update immediately for zone changes
- val isZoneChange = pausedInZone != insideSilentZone || zoneName != currentZoneName
-
- if (!isZoneChange && (now - lastNotificationTime) < NOTIFICATION_THROTTLE_MS) {
- return
- }
-
- lastNotificationTime = now
- updateNotification(lat, lon, pausedInZone, zoneName)
- }
-
// ========================================
// SYNCING & NETWORKING
// ========================================
@@ -466,14 +481,14 @@ class LocationForegroundService : Service() {
val baseDelay = calculateNextSyncDelay()
delay(baseDelay * 1000L)
- if (isOfflineMode || !locationUtils.isNetworkAvailable()) {
+ if (config.isOfflineMode || !locationUtils.isNetworkAvailable()) {
continue
}
// Use cached queue count
- if (endpoint.isNotBlank() && getCachedQueuedCount() > 0) {
+ if (config.endpoint.isNotBlank() && getCachedQueuedCount() > 0) {
try {
- val success = performSyncAndCheckSuccess(endpoint)
+ val success = performSyncAndCheckSuccess(config.endpoint)
if (success) {
if (consecutiveFailures > 0 && BuildConfig.DEBUG) {
@@ -526,23 +541,24 @@ class LocationForegroundService : Service() {
}
/**
- * Batch fetching - processes ALL queued items until empty.
- */
+ * Batch limit to prevent infinite syncing.
+ * Processes max 500 items (10 batches × 50 items) per sync cycle.
+ */
private suspend fun syncQueue(endpoint: String) = coroutineScope {
var totalProcessed = 0
var batchNumber = 1
- while (isActive) {
+ while (isActive && batchNumber <= MAX_BATCHES_PER_SYNC) {
val queued = dbHelper.getQueuedLocations(50)
if (queued.isEmpty()) {
if (BuildConfig.DEBUG && totalProcessed > 0) {
- Log.d(TAG, "Sync complete: $totalProcessed items processed in $batchNumber batches")
+ Log.d(TAG, "Sync complete: $totalProcessed items in $batchNumber batches")
}
break
}
if (BuildConfig.DEBUG) {
- Log.d(TAG, "Processing batch $batchNumber: ${queued.size} items")
+ Log.d(TAG, "Processing batch $batchNumber/$MAX_BATCHES_PER_SYNC: ${queued.size} items")
}
for (chunk in queued.chunked(10)) {
@@ -550,12 +566,12 @@ class LocationForegroundService : Service() {
val permanentlyFailedIds = mutableListOf<Long>()
// Separate retriable from permanently failed
- val (retriable, exceeded) = chunk.partition { it.retryCount < maxRetries }
+ val (retriable, exceeded) = chunk.partition { it.retryCount < config.maxRetries }
// Mark exceeded items for removal
permanentlyFailedIds.addAll(exceeded.map { it.queueId })
if (BuildConfig.DEBUG && exceeded.isNotEmpty()) {
- Log.w(TAG, "Removing ${exceeded.size} items that exceeded $maxRetries retries")
+ Log.w(TAG, "Removing ${exceeded.size} items that exceeded ${config.maxRetries} retries")
}
// Attempt only retriable items
@@ -578,10 +594,10 @@ class LocationForegroundService : Service() {
dbHelper.incrementRetryCount(queueId, "Send failed")
// Check if this increment pushed it over the limit
- if (item.retryCount + 1 >= maxRetries) {
+ if (item.retryCount + 1 >= config.maxRetries) {
permanentlyFailedIds.add(queueId)
if (BuildConfig.DEBUG) {
- Log.w(TAG, "Item $queueId reached max retries after this attempt")
+ Log.w(TAG, "Item $queueId reached max retries")
}
}
}
@@ -598,12 +614,10 @@ class LocationForegroundService : Service() {
}
batchNumber++
-
- // Safety check: prevent infinite loops
- if (batchNumber > 100) {
- Log.e(TAG, "Sync aborted: exceeded 100 batches (potential infinite loop)")
- break
- }
+ }
+
+ if (batchNumber > MAX_BATCHES_PER_SYNC && BuildConfig.DEBUG) {
+ Log.w(TAG, "Sync paused: reached batch limit. Remaining items will sync next cycle.")
}
// Invalidate cache after all syncing is done
@@ -622,15 +636,15 @@ class LocationForegroundService : Service() {
lastQueueCountCheck = 0
// Skip sending if offline mode or no endpoint
- if (endpoint.isBlank() || isOfflineMode) {
+ if (config.endpoint.isBlank() || config.isOfflineMode) {
if (BuildConfig.DEBUG) {
- Log.d(TAG, "Queued location $locationId - ${if (isOfflineMode) "offline mode" else "no endpoint"}")
+ Log.d(TAG, "Queued location $locationId - ${if (config.isOfflineMode) "offline mode" else "no endpoint"}")
}
return // Item stays in queue with retry_count = 0
}
// Immediate send mode (syncInterval = 0)
- if (syncIntervalSeconds == 0) {
+ if (config.syncIntervalSeconds == 0) {
Log.d(TAG, "Instant send")
val success = locationUtils.sendToEndpoint(payload, endpoint)
@@ -647,9 +661,9 @@ class LocationForegroundService : Service() {
}
private fun calculateNextSyncDelay(): Long {
- if (syncIntervalSeconds <= 0) {
+ if (config.syncIntervalSeconds <= 0) {
return if (getCachedQueuedCount() > 0) {
- retryIntervalSeconds.toLong()
+ config.retryIntervalSeconds.toLong()
} else {
30L
}
@@ -659,15 +673,15 @@ class LocationForegroundService : Service() {
if (!syncInitialized) {
lastSyncTime = now
syncInitialized = true
- return syncIntervalSeconds.toLong()
+ return config.syncIntervalSeconds.toLong()
}
val elapsedSeconds = (now - lastSyncTime) / 1000
- val remaining = syncIntervalSeconds - elapsedSeconds
+ val remaining = config.syncIntervalSeconds - elapsedSeconds
return if (remaining <= 0) {
lastSyncTime = now
- syncIntervalSeconds.toLong()
+ config.syncIntervalSeconds.toLong()
} else {
remaining
}
@@ -710,15 +724,57 @@ class LocationForegroundService : Service() {
.build()
}
+ /**
+ * Smart notification updates with throttling and distance checking.
+ * Only updates when:
+ * - Zone status changes (immediate)
+ * - Moved >10 meters
+ * - Time throttle passed (10s)
+ */
private fun updateNotification(
lat: Double? = null,
lon: Double? = null,
pausedInZone: Boolean = false,
- zoneName: String? = null
+ zoneName: String? = null,
+ forceUpdate: Boolean = false
) {
- // Use cached queue count
- val queuedCount = getCachedQueuedCount()
+ val now = System.currentTimeMillis()
+ val lastCoords = lastNotificationCoords
+
+ // Check if this is a zone change (always update immediately)
+ val isZoneChange = pausedInZone != insideSilentZone || zoneName != currentZoneName
+ // Apply smart filtering unless forced or zone change
+ if (!forceUpdate && !isZoneChange && lat != null && lon != null) {
+ // Throttle: don't update more than once per 10 seconds
+ if ((now - lastNotificationTime) < NOTIFICATION_THROTTLE_MS) {
+ return
+ }
+
+ // Distance check: only update if moved >2 meters
+ if (lastCoords != null) {
+ val distance = FloatArray(1)
+ android.location.Location.distanceBetween(
+ lastCoords.first, lastCoords.second,
+ lat, lon,
+ distance
+ )
+
+ // Skip if moved <2m AND queue count cache is still fresh
+ if (distance[0] < 2 && (now - lastQueueCountCheck) < QUEUE_COUNT_CACHE_MS) {
+ return
+ }
+ }
+ }
+
+ // Update last notification time and coordinates
+ lastNotificationTime = now
+ if (lat != null && lon != null) {
+ lastNotificationCoords = Pair(lat, lon)
+ }
+
+ // Build notification text
+ val queuedCount = getCachedQueuedCount()
val isCurrentlyPaused = pausedInZone || insideSilentZone
val activeZone = zoneName ?: currentZoneName
@@ -731,7 +787,7 @@ class LocationForegroundService : Service() {
else -> "Searching GPS..."
}
- // Only update if changed
+ // Only update if text changed
val cacheKey = "$statusText-$queuedCount"
if (cacheKey != lastNotificationText) {
lastNotificationText = cacheKey
@@ -784,55 +840,74 @@ class LocationForegroundService : Service() {
// CONFIGURATION HANDLING
// ========================================
+ /**
+ * Use ServiceConfig for cleaner configuration management.
+ */
private fun loadConfigFromIntent(intent: Intent?) {
- intent?.let {
- val extras = it.extras ?: Bundle()
-
- val keys = listOf(
- "endpoint", "interval", "minUpdateDistance", "syncInterval",
- "maxRetries", "accuracyThreshold", "filterInaccurateLocations",
- "retryInterval", "isOfflineMode"
- )
-
- for (key in keys) {
- if (intent.hasExtra(key)) {
- val rawValue = extras.get(key)
- val value = rawValue?.toString()?.removeSuffix(".0")
-
- if (value != null) {
- dbHelper.saveSetting(key, value)
- }
- }
- }
-
- if (it.hasExtra("fieldMap")) {
- val mapStr = it.getStringExtra("fieldMap")
- if (!mapStr.isNullOrBlank()) {
- dbHelper.saveSetting("fieldMap", mapStr)
- }
- }
+ // Load config using ServiceConfig utility
+ config = if (intent != null) {
+ ServiceConfig.fromIntent(intent, dbHelper)
+ } else {
+ ServiceConfig.fromDatabase(dbHelper)
}
-
- val saved = dbHelper.getAllSettings()
-
- endpoint = saved["endpoint"] ?: ""
- interval = saved["interval"]?.toLongOrNull() ?: 1000L
- minUpdateDistance = saved["minUpdateDistance"]?.toFloatOrNull() ?: 0f
- syncIntervalSeconds = saved["syncInterval"]?.toIntOrNull() ?: 0
- maxRetries = saved["maxRetries"]?.toIntOrNull() ?: 5
- accuracyThreshold = saved["accuracyThreshold"]?.toFloatOrNull() ?: 50.0f
- filterInaccurateLocations = saved["filterInaccurateLocations"]?.toBoolean() ?: true
- retryIntervalSeconds = saved["retryInterval"]?.toIntOrNull() ?: 300
- isOfflineMode = saved["isOfflineMode"]?.toBoolean() ?: false
- saved["fieldMap"]?.let {
+ // Parse fieldMap separately (remains as Map for payload building)
+ config.fieldMap?.let {
if (it.isNotBlank()) fieldMap = locationUtils.parseFieldMap(it)
}
if (BuildConfig.DEBUG) {
+ val batteryStatus = when(cachedBatteryStatus) {
+ 0 -> "Unknown"
+ 1 -> "Unplugged/Discharging"
+ 2 -> "Charging"
+ 3 -> "Full"
+ else -> "Unknown ($cachedBatteryStatus)"
+ }
+
Log.d(TAG, """
- Config: interval=${interval/1000}s, sync=${syncIntervalSeconds}s,
- endpoint=${if(endpoint.isBlank()) "none" else "set"}
+ ╔════════════════════════════════════════════════════════════════╗
+ ║ COLOTA LOCATION SERVICE CONFIGURATION ║
+ ╠════════════════════════════════════════════════════════════════╣
+ ║ GPS TRACKING ║
+ ╟────────────────────────────────────────────────────────────────╢
+ ║ Update Interval: ${config.interval}ms (${config.interval/1000.0}s)
+ ║ Min Update Distance: ${config.minUpdateDistance}m
+ ║ Accuracy Threshold: ${config.accuracyThreshold}m
+ ║ Filter Inaccurate: ${config.filterInaccurateLocations}
+ ╟────────────────────────────────────────────────────────────────╢
+ ║ NETWORK & SYNC ║
+ ╟────────────────────────────────────────────────────────────────╢
+ ║ Endpoint: ${if(config.endpoint.isBlank()) "⚠️ NOT CONFIGURED" else "✓ ${config.endpoint}"}
+ ║ Offline Mode: ${if(config.isOfflineMode) "✓ ENABLED" else "✗ Disabled"}
+ ║ Sync Mode: ${if(config.syncIntervalSeconds == 0) "⚡ INSTANT SEND" else "🕐 PERIODIC (${config.syncIntervalSeconds}s)"}
+ ║ Retry Interval: ${config.retryIntervalSeconds}s
+ ║ Max Retry Attempts: ${config.maxRetries}
+ ║ Max Batch Limit: $MAX_BATCHES_PER_SYNC batches × 50 items = ${MAX_BATCHES_PER_SYNC * 50} max/cycle
+ ╟────────────────────────────────────────────────────────────────╢
+ ║ PERFORMANCE OPTIMIZATION ║
+ ╟────────────────────────────────────────────────────────────────╢
+ ║ Queue Count Cache: ${QUEUE_COUNT_CACHE_MS/1000}s
+ ║ Battery Check Cache: ${BATTERY_CHECK_INTERVAL_MS/1000}s
+ ║ Notification Throttle: ${NOTIFICATION_THROTTLE_MS/1000}s
+ ╟────────────────────────────────────────────────────────────────╢
+ ║ FIELD MAPPING ║
+ ╟────────────────────────────────────────────────────────────────╢
+ ║ Custom Fields: ${if(fieldMap != null && fieldMap!!.isNotEmpty()) "✓ YES (${fieldMap!!.size} mappings)" else "✗ Using Defaults"}
+ ${if(fieldMap != null && fieldMap!!.isNotEmpty()) {
+ fieldMap!!.entries.joinToString("\n") {
+ "║ ${it.key.padEnd(20)} → ${it.value}"
+ }
+ } else ""}
+ ╟────────────────────────────────────────────────────────────────╢
+ ║ CURRENT SERVICE STATE ║
+ ╟────────────────────────────────────────────────────────────────╢
+ ║ Tracking Status: ✓ ACTIVE
+ ║ Silent Zone: ${if(insideSilentZone) "⏸️ PAUSED in '$currentZoneName'" else "✓ Not in zone"}
+ ║ Battery Level: $cachedBatteryLevel% ($batteryStatus)
+ ║ Queued Locations: $cachedQueuedCount items
+ ║ Last Location: ${if(lastKnownLocation != null) "%.5f, %.5f".format(lastKnownLocation!!.latitude, lastKnownLocation!!.longitude) else "N/A"}
+ ╚════════════════════════════════════════════════════════════════╝
""".trimIndent())
}
}
diff --git a/android/app/src/main/java/com/locata/LocationServiceModule.kt b/android/app/src/main/java/com/locata/LocationServiceModule.kt
index f1988fd1..078153f5 100644
--- a/android/app/src/main/java/com/locata/LocationServiceModule.kt
+++ b/android/app/src/main/java/com/locata/LocationServiceModule.kt
@@ -10,8 +10,6 @@ import android.os.PowerManager
import android.provider.Settings
import android.net.Uri
import android.content.Intent
-import android.net.Network
-import android.net.ConnectivityManager.NetworkCallback
import android.os.Build
import android.util.Log
import com.facebook.react.bridge.*
@@ -34,43 +32,10 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
private val dbHelper = LocationDatabaseHelper.getInstance(reactContext)
// Use a fixed thread pool instead of unlimited threads
- private val dbExecutor: ExecutorService = Executors.newFixedThreadPool(2)
-
- // Cache connectivity manager
- private val connectivityManager by lazy {
- reactContext.getSystemService(Context.CONNECTIVITY_SERVICE) as android.net.ConnectivityManager
- }
-
- // Network state listener to avoid polling
- private val networkCallback = object : NetworkCallback() {
- override fun onAvailable(network: Network) {
- // Network just became available
- dbExecutor.execute {
- val queuedCount = dbHelper.getQueuedCount()
- if (queuedCount > 0) {
- val syncInterval = dbHelper.getSetting("syncInterval", "0")?.toIntOrNull() ?: 0
-
- if (syncInterval == 0) {
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "Network available, triggering manual flush for $queuedCount items")
- }
- val intent = Intent(
- reactApplicationContext,
- LocationForegroundService::class.java
- ).apply {
- action = "com.Colota.ACTION_MANUAL_FLUSH"
- }
- try {
- reactApplicationContext.startService(intent)
- } catch (e: Exception) {
- Log.e(TAG, "Failed to trigger manual flush", e)
- }
- } else if (BuildConfig.DEBUG) {
- Log.d(TAG, "Network available, $queuedCount items queued for next sync interval")
- }
- }
- }
- }
+ private val dbExecutor: ExecutorService = if (Config.DB_THREAD_POOL_SIZE == 1) {
+ Executors.newSingleThreadExecutor()
+ } else {
+ Executors.newFixedThreadPool(Config.DB_THREAD_POOL_SIZE)
}
// Coroutine scope for async operations
@@ -79,15 +44,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
init {
reactContextStatic = reactContext
reactContext.addLifecycleEventListener(this)
-
- // Register network callback
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
- try {
- connectivityManager.registerDefaultNetworkCallback(networkCallback)
- } catch (e: Exception) {
- Log.e(TAG, "Failed to register network callback", e)
- }
- }
}
companion object {
@@ -97,11 +53,16 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@Volatile
private var isAppInForeground: Boolean = true
+ private object Config {
+ const val DB_THREAD_POOL_SIZE = 1
+ const val EXECUTOR_SHUTDOWN_TIMEOUT_MS = 800L
+ }
+
/**
* Emits location updates to the React Native 'onLocationUpdate' listener.
*/
@JvmStatic
- fun sendLocationEvent(location: android.location.Location): Boolean {
+ fun sendLocationEvent(location: android.location.Location, battery: Int, batteryStatus: Int): Boolean {
// Check foreground state first (cheapest check)
if (!isAppInForeground) return false
@@ -123,6 +84,8 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
putDouble("speed", location.speed.toDouble())
putDouble("bearing", if (location.hasBearing()) location.bearing.toDouble() else 0.0)
putDouble("timestamp", location.time.toDouble())
+ putInt("battery", battery)
+ putInt("batteryStatus", batteryStatus)
}
context
@@ -173,19 +136,19 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
override fun onHostDestroy() {
isAppInForeground = false
- // Cleanup network callback
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
- try {
- connectivityManager.unregisterNetworkCallback(networkCallback)
- } catch (e: Exception) {
- // Already unregistered or never registered
- if (BuildConfig.DEBUG) {
- Log.d(TAG, "Network callback cleanup: ${e.message}")
- }
+ // Cancel coroutines
+ moduleScope.cancel()
+
+ // Properly shutdown executor (YOU REMOVED THIS!)
+ dbExecutor.shutdown()
+ try {
+ if (!dbExecutor.awaitTermination(Config.EXECUTOR_SHUTDOWN_TIMEOUT_MS, java.util.concurrent.TimeUnit.MILLISECONDS)) {
+ dbExecutor.shutdownNow()
}
+ } catch (e: InterruptedException) {
+ dbExecutor.shutdownNow()
+ Thread.currentThread().interrupt()
}
-
- moduleScope.cancel()
}
// ==============================================================
@@ -323,10 +286,7 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@ReactMethod
fun manualFlush(promise: Promise) {
try {
- val intent = Intent(reactApplicationContext, LocationForegroundService::class.java).apply {
- action = "com.Colota.ACTION_MANUAL_FLUSH"
- }
- reactApplicationContext.startService(intent)
+ startServiceWithAction(LocationForegroundService.ACTION_MANUAL_FLUSH)
promise.resolve(true)
} catch (e: Exception) {
Log.e(TAG, "Manual flush failed", e)
@@ -372,6 +332,19 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
// GEOFENCE OPERATIONS
// ==============================================================
+ // Helper function to reduce duplication
+ private fun triggerZoneRecheck() {
+ try {
+ startServiceWithAction(LocationForegroundService.ACTION_RECHECK_ZONE)
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to trigger zone recheck", e)
+ }
+ }
+
+ /**
+ * Creates a geofence and invalidates cache to ensure the
+ * Foreground Service recognizes the change immediately.
+ */
@ReactMethod
fun createGeofence(
name: String,
@@ -382,22 +355,17 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
promise: Promise
) = executeAsync(promise) {
val result = locationUtils.insertGeofence(name, lat, lon, radius, pause)
-
- // OPTIMIZATION 8: Trigger zone recheck after creating geofence
if (result > 0) {
- try {
- val intent = Intent(reactApplicationContext, LocationForegroundService::class.java).apply {
- action = "com.Colota.RECHECK_SILENT_ZONE"
- }
- reactApplicationContext.startService(intent)
- } catch (e: Exception) {
- Log.e(TAG, "Failed to trigger zone recheck", e)
- }
+ locationUtils.invalidateGeofenceCache()
+ triggerZoneRecheck()
}
-
result
}
+ /**
+ * Fetches all geofences for the UI.
+ * Does not invalidate cache as this is a read-only operation.
+ */
@ReactMethod
fun getGeofences(promise: Promise) = executeAsync(promise) {
locationUtils.getGeofencesAsArray()
@@ -415,38 +383,24 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
promise: Promise
) = executeAsync(promise) {
val result = locationUtils.updateGeofence(id, name, lat, lon, radius, enabled, pause)
-
- // Trigger zone recheck after updating geofence
if (result) {
- try {
- val intent = Intent(reactApplicationContext, LocationForegroundService::class.java).apply {
- action = "com.Colota.RECHECK_SILENT_ZONE"
- }
- reactApplicationContext.startService(intent)
- } catch (e: Exception) {
- Log.e(TAG, "Failed to trigger zone recheck", e)
- }
+ locationUtils.invalidateGeofenceCache()
+ triggerZoneRecheck()
}
-
result
}
- @ReactMethod
+ /**
+ * Deletes a geofence and invalidates cache to ensure the
+ * Foreground Service recognizes the change immediately.
+ */
+ @ReactMethod
fun deleteGeofence(id: Int, promise: Promise) = executeAsync(promise) {
val result = locationUtils.deleteGeofence(id)
-
- // Trigger zone recheck after deleting geofence
if (result) {
- try {
- val intent = Intent(reactApplicationContext, LocationForegroundService::class.java).apply {
- action = "com.Colota.RECHECK_SILENT_ZONE"
- }
- reactApplicationContext.startService(intent)
- } catch (e: Exception) {
- Log.e(TAG, "Failed to trigger zone recheck", e)
- }
+ locationUtils.invalidateGeofenceCache()
+ triggerZoneRecheck()
}
-
result
}
@@ -463,7 +417,6 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
if (loc == null) {
promise.resolve(null)
} else {
- // Run on executor to avoid blocking
dbExecutor.execute {
try {
promise.resolve(locationUtils.getSilentZone(loc))
@@ -482,26 +435,42 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
+ @ReactMethod
+ fun recheckZoneSettings(promise: Promise) {
+ triggerZoneRecheck()
+ promise.resolve(null)
+ }
+
@ReactMethod
fun forceExitZone(promise: Promise) {
try {
- val intent = Intent(reactApplicationContext, LocationForegroundService::class.java).apply {
- action = LocationForegroundService.ACTION_FORCE_EXIT_ZONE
- }
-
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- reactApplicationContext.startForegroundService(intent)
- } else {
- reactApplicationContext.startService(intent)
- }
-
+ startServiceWithAction(LocationForegroundService.ACTION_FORCE_EXIT_ZONE)
promise.resolve(true)
} catch (e: Exception) {
- Log.e(TAG, "Failed to force exit zone", e)
promise.reject("FORCE_EXIT_ERROR", e.message, e)
}
}
+ // ==============================================================
+ // STATISTICS & ANALYTICS (Future)
+ // ==============================================================
+
+ // TODO: Add when implementing statistics feature
+ // @ReactMethod
+ // fun getLocationStats(timeRange: String, promise: Promise) = executeAsync(promise) {
+ // // Implementation here
+ // }
+
+ // @ReactMethod
+ // fun getDistanceTraveled(startTime: Long, endTime: Long, promise: Promise) = executeAsync(promise) {
+ // // Implementation here
+ // }
+
+ // @ReactMethod
+ // fun getSpeedAnalytics(promise: Promise) = executeAsync(promise) {
+ // // Implementation here
+ // }
+
// ==============================================================
// SETTINGS PERSISTENCE
// ==============================================================
@@ -580,6 +549,24 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
}
}
}
+
+ // Add helper for all service intents
+ private fun startServiceWithAction(action: String) {
+ try {
+ val intent = Intent(reactApplicationContext, LocationForegroundService::class.java).apply {
+ this.action = action
+ }
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ reactApplicationContext.startForegroundService(intent)
+ } else {
+ reactApplicationContext.startService(intent)
+ }
+ } catch (e: Exception) {
+ Log.e(TAG, "Failed to start service with action: $action", e)
+ throw e
+ }
+ }
}
// Extension functions for safer ReadableMap access
diff --git a/android/app/src/main/java/com/locata/LocationsUtils.kt b/android/app/src/main/java/com/locata/LocationsUtils.kt
index 52c03a5d..aaaef9c5 100644
--- a/android/app/src/main/java/com/locata/LocationsUtils.kt
+++ b/android/app/src/main/java/com/locata/LocationsUtils.kt
@@ -33,17 +33,34 @@ class LocationUtils(private val context: Context) {
companion object {
private const val TAG = "LocationUtils"
private const val EARTH_RADIUS_METERS = 6371000.0
- private const val CONNECTION_TIMEOUT = 15000
- private const val READ_TIMEOUT = 15000
+ private const val CONNECTION_TIMEOUT = 10000
+ private const val READ_TIMEOUT = 10000
}
// Lazy initialization - only created when first accessed
private val dbHelper by lazy { LocationDatabaseHelper.getInstance(context) }
// Cache connectivity manager to avoid repeated getSystemService calls
- private val connectivityManager by lazy {
- context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
+ private val connectivityManager: ConnectivityManager by lazy {
+ context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
}
+
+ @Volatile
+ private var cachedGeofences: List<CachedGeofence>? = null
+ private var lastGeofenceCacheTime: Long = 0
+ private val GEOFENCE_CACHE_MS = 30000L // 30 seconds
+
+ data class CachedGeofence(
+ val name: String,
+ val lat: Double,
+ val lon: Double,
+ val radius: Double
+ )
+
+ @Volatile
+ private var lastNetworkCheck: Boolean = true
+ private var lastNetworkCheckTime: Long = 0
+ private val NETWORK_CHECK_CACHE_MS = 5000L // 5 seconds
// ========================================
// NETWORK & SYNC
@@ -95,7 +112,6 @@ class LocationUtils(private val context: Context) {
var connection: java.net.HttpURLConnection? = null
try {
- Log.d(TAG, "Sending")
val url = URL(endpoint)
connection = url.openConnection() as java.net.HttpURLConnection
@@ -121,10 +137,9 @@ class LocationUtils(private val context: Context) {
val responseCode = connection.responseCode
if (responseCode in 200..299) {
-
- Log.d(TAG, "Location successfully sent")
- // Success - optionally read response body
- // connection.inputStream.use { it.bufferedReader().readText() }
+ if (BuildConfig.DEBUG) {
+ Log.d(TAG, "Location successfully sent")
+ }
true
} else {
// Read error body for debugging
@@ -147,21 +162,43 @@ class LocationUtils(private val context: Context) {
}
/**
- * Checks for an active, validated internet connection.
- * Uses cached ConnectivityManager for better performance.
- */
+ * Checks for an active, validated internet connection.
+ * Cached to avoid excessive system calls.
+ */
fun isNetworkAvailable(): Boolean {
- return try {
- val activeNetwork = connectivityManager.activeNetwork ?: return false
- val capabilities = connectivityManager.getNetworkCapabilities(activeNetwork)
- ?: return false
+ val now = System.currentTimeMillis()
+
+ // Return cached result if fresh
+ if ((now - lastNetworkCheckTime) < NETWORK_CHECK_CACHE_MS) {
+ return lastNetworkCheck
+ }
+
+ lastNetworkCheck = try {
+ val network = connectivityManager.activeNetwork
+ if (network == null) {
+ lastNetworkCheckTime = now
+ return false
+ }
+
+ val capabilities = connectivityManager.getNetworkCapabilities(network)
+ if (capabilities == null) {
+ lastNetworkCheckTime = now
+ return false
+ }
+ // Check for both internet capability and that the OS has validated the connection
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
- capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
+ capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
} catch (e: SecurityException) {
Log.e(TAG, "Missing network permission", e)
false
+ } catch (e: Exception) {
+ Log.e(TAG, "Network check failed", e)
+ false
}
+
+ lastNetworkCheckTime = now
+ return lastNetworkCheck
}
// ========================================
@@ -184,6 +221,27 @@ class LocationUtils(private val context: Context) {
return EARTH_RADIUS_METERS * 2 * atan2(sqrt(a), sqrt(1 - a))
}
+ /**
+ * Fast distance check without square root for geofence detection.
+ * Returns true if within radius (cheaper than full Haversine).
+ */
+ fun isWithinRadius(lat1: Double, lon1: Double, lat2: Double, lon2: Double, radiusMeters: Double): Boolean {
+ // Quick rejection test using simple lat/lon differences
+ val latDiff = Math.abs(lat1 - lat2)
+ val lonDiff = Math.abs(lon1 - lon2)
+
+ // Rough approximation: 1 degree ≈ 111km at equator
+ val maxDegreeDiff = radiusMeters / 111000.0
+
+ // Quick rejection: if way outside bounding box, skip expensive calculation
+ if (latDiff > maxDegreeDiff || lonDiff > maxDegreeDiff) {
+ return false
+ }
+
+ // Only do full Haversine if within rough bounding box
+ return calculateDistance(lat1, lon1, lat2, lon2) <= radiusMeters
+ }
+
// ========================================
// DATA CONVERSION
// ========================================
@@ -289,26 +347,86 @@ class LocationUtils(private val context: Context) {
// ========================================
/**
- * Checks if location is within any active silent zone.
- * Returns immediately on first match for better performance.
- */
- fun getSilentZone(location: Location): String? {
+ * Refreshes geofence cache from database
+ */
+ private fun refreshGeofenceCache(): List<CachedGeofence> {
+ val fences = mutableListOf<CachedGeofence>()
+
dbHelper.readableDatabase.query(
LocationDatabaseHelper.TABLE_GEOFENCES,
arrayOf("name", "latitude", "longitude", "radius"),
"enabled = 1 AND pause_tracking = 1",
null, null, null, null
).use { cursor ->
+ val nameIdx = cursor.getColumnIndexOrThrow("name")
+ val latIdx = cursor.getColumnIndexOrThrow("latitude")
+ val lonIdx = cursor.getColumnIndexOrThrow("longitude")
+ val radiusIdx = cursor.getColumnIndexOrThrow("radius")
+
while (cursor.moveToNext()) {
- val fenceLat = cursor.getDouble(1)
- val fenceLon = cursor.getDouble(2)
- val radius = cursor.getDouble(3)
-
- if (calculateDistance(location.latitude, location.longitude, fenceLat, fenceLon) <= radius) {
- return cursor.getString(0)
- }
+ fences.add(CachedGeofence(
+ cursor.getString(nameIdx),
+ cursor.getDouble(latIdx),
+ cursor.getDouble(lonIdx),
+ cursor.getDouble(radiusIdx)
+ ))
}
}
+
+ cachedGeofences = fences
+ lastGeofenceCacheTime = System.currentTimeMillis()
+
+ if (BuildConfig.DEBUG) {
+ Log.d(TAG, "Geofence cache refreshed: ${fences.size} zones")
+ }
+
+ return fences
+ }
+
+ /**
+ * Gets geofences from cache or refreshes if stale
+ */
+ private fun getGeofences(): List<CachedGeofence> {
+ val now = System.currentTimeMillis()
+
+ return if (cachedGeofences == null || (now - lastGeofenceCacheTime) > GEOFENCE_CACHE_MS) {
+ refreshGeofenceCache()
+ } else {
+ cachedGeofences!!
+ }
+ }
+
+ /**
+ * Invalidates cache when geofences change
+ */
+ fun invalidateGeofenceCache() {
+ cachedGeofences = null
+ lastGeofenceCacheTime = 0
+
+ if (BuildConfig.DEBUG) {
+ Log.d(TAG, "Geofence cache invalidated")
+ }
+ }
+
+ /**
+ * Checks if location is within any active silent zone.
+ * Returns immediately on first match for better performance.
+ */
+ fun getSilentZone(location: Location): String? {
+ val fences = getGeofences()
+
+ for (fence in fences) {
+ if (isWithinRadius(
+ location.latitude,
+ location.longitude,
+ fence.lat,
+ fence.lon,
+ fence.radius
+ )) {
+ return fence.name
+ }
+ }
+
return null
}
diff --git a/android/app/src/main/java/com/locata/ServiceConfig.kt b/android/app/src/main/java/com/locata/ServiceConfig.kt
new file mode 100644
index 00000000..3079b46a
--- /dev/null
+++ b/android/app/src/main/java/com/locata/ServiceConfig.kt
@@ -0,0 +1,107 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+package com.Colota
+
+import android.content.Intent
+import android.os.Bundle
+
+/**
+ * Centralized service configuration to eliminate duplication across:
+ * - LocationBootReceiver
+ * - LocationServiceModule
+ * - LocationForegroundService
+ */
+data class ServiceConfig(
+ val endpoint: String = "",
+ val interval: Long = 1000L,
+ val minUpdateDistance: Float = 0f,
+ val syncIntervalSeconds: Int = 0,
+ val maxRetries: Int = 5,
+ val accuracyThreshold: Float = 50.0f,
+ val filterInaccurateLocations: Boolean = true,
+ val retryIntervalSeconds: Int = 300,
+ val isOfflineMode: Boolean = false,
+ val fieldMap: String? = null
+) {
+ companion object {
+ /**
+ * Loads configuration from database settings.
+ */
+ fun fromDatabase(dbHelper: LocationDatabaseHelper): ServiceConfig {
+ val saved = dbHelper.getAllSettings()
+
+ return ServiceConfig(
+ endpoint = saved["endpoint"] ?: "",
+ interval = saved["interval"]?.toLongOrNull() ?: 1000L,
+ minUpdateDistance = saved["minUpdateDistance"]?.toFloatOrNull() ?: 0f,
+ syncIntervalSeconds = saved["syncInterval"]?.toIntOrNull() ?: 0,
+ maxRetries = saved["maxRetries"]?.toIntOrNull() ?: 5,
+ accuracyThreshold = saved["accuracyThreshold"]?.toFloatOrNull() ?: 50.0f,
+ filterInaccurateLocations = saved["filterInaccurateLocations"]?.toBoolean() ?: true,
+ retryIntervalSeconds = saved["retryInterval"]?.toIntOrNull() ?: 300,
+ isOfflineMode = saved["isOfflineMode"]?.toBoolean() ?: false,
+ fieldMap = saved["fieldMap"]
+ )
+ }
+
+ /**
+ * Loads configuration from Intent extras (for service start).
+ */
+ fun fromIntent(intent: Intent, dbHelper: LocationDatabaseHelper): ServiceConfig {
+ val extras = intent.extras ?: return fromDatabase(dbHelper)
+
+ // Load from database first, then override with intent extras
+ val dbConfig = fromDatabase(dbHelper)
+
+ return ServiceConfig(
+ endpoint = extras.getString("endpoint") ?: dbConfig.endpoint,
+ interval = extras.getLongOrDefault("interval", dbConfig.interval),
+ minUpdateDistance = extras.getFloatOrDefault("minUpdateDistance", dbConfig.minUpdateDistance),
+ syncIntervalSeconds = extras.getIntOrDefault("syncInterval", dbConfig.syncIntervalSeconds),
+ maxRetries = extras.getIntOrDefault("maxRetries", dbConfig.maxRetries),
+ accuracyThreshold = extras.getFloatOrDefault("accuracyThreshold", dbConfig.accuracyThreshold),
+ filterInaccurateLocations = extras.getBooleanOrDefault("filterInaccurateLocations", dbConfig.filterInaccurateLocations),
+ retryIntervalSeconds = extras.getIntOrDefault("retryInterval", dbConfig.retryIntervalSeconds),
+ isOfflineMode = extras.getBooleanOrDefault("isOfflineMode", dbConfig.isOfflineMode),
+ fieldMap = extras.getStringOrDefault("fieldMap", dbConfig.fieldMap)
+ )
+ }
+ }
+
+ /**
+ * Converts config to Intent extras for service communication.
+ */
+ fun toIntent(intent: Intent): Intent {
+ return intent.apply {
+ putExtra("interval", interval)
+ putExtra("minUpdateDistance", minUpdateDistance)
+ putExtra("endpoint", endpoint)
+ putExtra("syncInterval", syncIntervalSeconds)
+ putExtra("accuracyThreshold", accuracyThreshold)
+ putExtra("filterInaccurateLocations", filterInaccurateLocations)
+ putExtra("maxRetries", maxRetries)
+ putExtra("retryInterval", retryIntervalSeconds)
+ putExtra("isOfflineMode", isOfflineMode)
+ fieldMap?.let { putExtra("fieldMap", it) }
+ }
+ }
+}
+
+// Extension functions for safer Bundle access
+private fun Bundle.getStringOrDefault(key: String, default: String?): String? =
+ if (containsKey(key)) getString(key) else default
+
+private fun Bundle.getLongOrDefault(key: String, default: Long): Long =
+ if (containsKey(key)) getLong(key) else default
+
+private fun Bundle.getFloatOrDefault(key: String, default: Float): Float =
+ if (containsKey(key)) getFloat(key) else default
+
+private fun Bundle.getIntOrDefault(key: String, default: Int): Int =
+ if (containsKey(key)) getInt(key) else default
+
+private fun Bundle.getBooleanOrDefault(key: String, default: Boolean): Boolean =
+ if (containsKey(key)) getBoolean(key) else default
\ No newline at end of file
diff --git a/package.json b/package.json
index 03362090..b2febbde 100644
--- a/package.json
+++ b/package.json
@@ -8,7 +8,7 @@
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
"format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,md}\"",
"format:check": "prettier --check \"**/*.{js,jsx,ts,tsx,json,md}\"",
- "test": "jest",
+ "test": "jest --passWithNoTests",
"test:coverage": "jest --coverage",
"clean": "cd android && gradlew clean && cd ..",
"dev-android": "npx react-native run-android",
diff --git a/src/components/features/dashboard/DashboardMap.tsx b/src/components/features/dashboard/DashboardMap.tsx
index f1e237ed..e373c227 100644
--- a/src/components/features/dashboard/DashboardMap.tsx
+++ b/src/components/features/dashboard/DashboardMap.tsx
@@ -321,8 +321,7 @@ export function DashboardMap({ coords, tracking, activeZoneName }: Props) {
const center = ol.proj.fromLonLat([zone.lon, zone.lat]);
const circle = new ol.geom.Circle(center, zone.radius);
const feature = new ol.Feature(circle);
-
- console.log("zone" + zone.pauseTracking)
+
feature.setStyle(
new ol.style.Style({
stroke: new ol.style.Stroke({
@@ -400,9 +399,6 @@ export function DashboardMap({ coords, tracking, activeZoneName }: Props) {
const markerIcon = markerEl.querySelector(".marker");
const markerPulse = markerEl.querySelector(".marker-pulse");
-
- console.log("markerIcon" + markerIcon)
- console.log("markerPulse" + markerPulse)
if (markerIcon && markerPulse) {
const isActive = data.tracking && !data.isPaused;
const markerColor = data.isPaused ? "${colors.textDisabled}" : "${
@@ -411,7 +407,6 @@ export function DashboardMap({ coords, tracking, activeZoneName }: Props) {
markerIcon.style.background = markerColor;
markerPulse.style.borderColor = markerColor;
- console.log("isActive" + isActive)
markerPulse.style.display = isActive ? "block" : "none";
}
}
diff --git a/src/hooks/useLocationTracking.ts b/src/hooks/useLocationTracking.ts
index d8e151e9..44d18e17 100644
--- a/src/hooks/useLocationTracking.ts
+++ b/src/hooks/useLocationTracking.ts
@@ -94,7 +94,6 @@ export function useLocationTracking(
useEffect(() => {
if (tracking && !listenerRef.current) {
console.log("[useLocationTracking] 📡 Attaching native listener");
-
listenerRef.current = locationEventEmitter.addListener(
"onLocationUpdate",
(event: any) => {
diff --git a/src/screens/ExportDataScreen.tsx b/src/screens/ExportDataScreen.tsx
index 767ef366..9b9428c3 100644
--- a/src/screens/ExportDataScreen.tsx
+++ b/src/screens/ExportDataScreen.tsx
@@ -16,21 +16,11 @@ import {
} from "react-native";
import { Container, Card, SectionTitle, Divider } from "../components";
import { useTheme } from "../hooks/useTheme";
-import { ThemeColors } from "../types/global";
+import { ThemeColors, LocationCoords } from "../types/global";
import NativeLocationService from "../services/NativeLocationService";
import RNFS from "react-native-fs";
import Share from "react-native-share"; // Use react-native-share instead
-interface LocationData {
- id: number;
- timestamp: number;
- latitude: number;
- longitude: number;
- accuracy: number;
- altitude: number;
- speed: number;
- battery: number;
-}
type ExportFormat = "csv" | "geojson" | "gpx" | "kml";
@@ -151,7 +141,7 @@ export function ExportDataScreen() {
setExportProgress("Fetching location data...");
try {
- const data: LocationData[] = await NativeLocationService.getExportData();
+ const data: LocationCoords[] = await NativeLocationService.getExportData();
setExportProgress(`Converting ${data.length} locations...`);
@@ -501,14 +491,15 @@ const FormatOption = ({
// --- Format Conversion Functions ---
-const convertToCSV = (data: LocationData[]): string => {
+const convertToCSV = (data: LocationCoords[]): string => {
const headers =
"id,timestamp,iso_time,latitude,longitude,accuracy,altitude,speed,battery\n";
const rows = data
- .map((item) => {
- const isoTime = new Date(item.timestamp).toISOString();
+ .map((item, i) => {
+ const timestamp = item.timestamp ?? Date.now();
+ const isoTime = new Date(timestamp).toISOString();
return [
- item.id,
+ i,
item.timestamp,
isoTime,
item.latitude,
@@ -523,8 +514,8 @@ const convertToCSV = (data: LocationData[]): string => {
return headers + rows;
};
-const convertToGeoJSON = (data: LocationData[]): string => {
- const features = data.map((item) => {
+const convertToGeoJSON = (data: LocationCoords[]): string => {
+ const features = data.map((item, i) => {
const timestamp = item.timestamp ? new Date(item.timestamp) : new Date();
const timeStr = isNaN(timestamp.getTime())
? new Date().toISOString()
@@ -537,7 +528,7 @@ const convertToGeoJSON = (data: LocationData[]): string => {
coordinates: [item.longitude || 0, item.latitude || 0],
},
properties: {
- id: item.id,
+ id: i,
accuracy: item.accuracy,
altitude: item.altitude,
speed: item.speed,
@@ -557,7 +548,7 @@ const convertToGeoJSON = (data: LocationData[]): string => {
);
};
-const convertToGPX = (data: LocationData[]): string => {
+const convertToGPX = (data: LocationCoords[]): string => {
let gpx = `<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="Colota" xmlns="http://www.topografix.com/GPX/1/1">
<metadata>
@@ -569,13 +560,14 @@ const convertToGPX = (data: LocationData[]): string => {
<trkseg>`;
data.forEach((item) => {
- const time = new Date(item.timestamp).toISOString();
+ const timestamp = item.timestamp ?? Date.now();
+ const isoTime = new Date(timestamp).toISOString();
gpx += `
<trkpt lat="${item.latitude.toFixed(6)}" lon="${item.longitude.toFixed(
6
)}">
<ele>${item.altitude || 0}</ele>
- <time>${time}</time>
+ <time>${isoTime}</time>
<extensions>
<accuracy>${item.accuracy || 0}</accuracy>
<speed>${item.speed || 0}</speed>
@@ -591,7 +583,7 @@ const convertToGPX = (data: LocationData[]): string => {
return gpx;
};
-const convertToKML = (data: LocationData[]): string => {
+const convertToKML = (data: LocationCoords[]): string => {
let kml = `<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
@@ -621,10 +613,12 @@ const convertToKML = (data: LocationData[]): string => {
// Add individual points as Placemarks
data.forEach((item) => {
- const time = new Date(item.timestamp).toISOString();
+
+ const timestamp = item.timestamp ?? Date.now();
+ const isoTime = new Date(timestamp).toISOString();
kml += `
<Placemark>
- <TimeStamp><when>${time}</when></TimeStamp>
+ <TimeStamp><when>${isoTime}</when></TimeStamp>
<description>Accuracy: ${item.accuracy}m, Speed: ${
item.speed
}m/s</description>
diff --git a/src/screens/GeofenceScreen.tsx b/src/screens/GeofenceScreen.tsx
index d18f4eff..ed18a9d3 100644
--- a/src/screens/GeofenceScreen.tsx
+++ b/src/screens/GeofenceScreen.tsx
@@ -201,6 +201,7 @@ export function GeofenceScreen({}: ScreenProps) {
});
await loadGeofences();
DeviceEventEmitter.emit("geofenceUpdated");
+ await NativeLocationService.recheckZoneSettings();
} catch {
Alert.alert("Error", "Failed to update geofence.");
}
diff --git a/src/screens/LocationInspectorScreen.tsx b/src/screens/LocationInspectorScreen.tsx
index 792998ae..28d7fe5b 100644
--- a/src/screens/LocationInspectorScreen.tsx
+++ b/src/screens/LocationInspectorScreen.tsx
@@ -30,7 +30,7 @@ interface LocationData {
accuracy?: number;
bearing?: number;
battery: number;
- batteryStatus: number;
+ battery_status: number;
last_error?: string;
}
@@ -60,14 +60,15 @@ type TableType = "locations" | "queue";
*/
const LocationItem = memo(({ item, colors, isQueue }: LocationItemProps) => {
const getBatteryStatus = (status: number): string => {
+ console.log("batterystatus" + status)
switch (status) {
+ case 0:
+ return "Unknown";
+ case 1:
+ return "Unplugged";
case 2:
- return "⚡ Charging";
+ return "Charging";
case 3:
- return "Discharging";
- case 4:
- return "Not Charging";
- case 5:
return "Full";
default:
return "Unknown";
@@ -123,8 +124,8 @@ const LocationItem = memo(({ item, colors, isQueue }: LocationItemProps) => {
>
<Metric label="Battery" value={`${item.battery}%`} colors={colors} />
<Metric
- label="Status"
- value={getBatteryStatus(item.batteryStatus)}
+ label="Battery Status"
+ value={getBatteryStatus(item.battery_status)}
colors={colors}
/>
<View style={styles.spacer} />
diff --git a/src/screens/SettingsScreen.tsx b/src/screens/SettingsScreen.tsx
index 74d9dc66..2398cfdc 100644
--- a/src/screens/SettingsScreen.tsx
+++ b/src/screens/SettingsScreen.tsx
@@ -255,7 +255,6 @@ export function SettingsScreen({ navigation }: ScreenProps) {
if (fieldMap.bs) payload[fieldMap.bs] = 0;
if (fieldMap.tst) {
payload[fieldMap.tst] = Math.floor(Date.now() / 1000);
- console.log(payload);
}
const response = await fetch(endpointInput, {
diff --git a/src/services/NativeLocationService.ts b/src/services/NativeLocationService.ts
index 3ea296ad..4bae3549 100644
--- a/src/services/NativeLocationService.ts
+++ b/src/services/NativeLocationService.ts
@@ -377,6 +377,20 @@ class NativeLocationService {
);
}
+ /**
+ * Triggers immediate recheck of silent zone settings
+ * Use after modifying geofence pause settings to update notification instantly
+ */
+ static async recheckZoneSettings(): Promise<void> {
+ this.ensureModule();
+ console.log("[NativeLocationService] Triggering zone settings recheck");
+ try {
+ await LocationServiceModule.recheckZoneSettings();
+ } catch (error) {
+ console.error("[NativeLocationService] ❌ Recheck failed:", error);
+ }
+ }
+
// ============================================================================
// SETTINGS OPERATIONS
// ============================================================================