Skip to content

Colota - Android GPS Location tracker

feat: warn user when Location Services are off (#312)

Max Dietrich23b09bab9ec4
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.kt
index 9e6334bd..7bdb7930 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
@@ -210,6 +210,10 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
@JvmStatic
fun sendChargingStateEvent(isPlugged: Boolean): Boolean =
emit("onChargingStateChanged") { putBoolean("isPlugged", isPlugged) }
+
+ @JvmStatic
+ fun sendLocationStateEvent(locationEnabled: Boolean): Boolean =
+ emit("onLocationStateChanged") { putBoolean("locationEnabled", locationEnabled) }
}
override fun getName(): String = "LocationServiceModule"
@@ -726,6 +730,16 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :
promise.resolve(deviceInfo.isBatteryCritical())
}
+ @ReactMethod
+ fun isLocationEnabled(promise: Promise) {
+ promise.resolve(deviceInfo.isLocationEnabled())
+ }
+
+ @ReactMethod
+ fun openLocationSettings(promise: Promise) {
+ promise.resolve(deviceInfo.openLocationSettings())
+ }
+
@ReactMethod
fun requestIgnoreBatteryOptimizations(promise: Promise) {
try {
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.kt
index 9725e239..ac42f5b8 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
@@ -6,11 +6,16 @@
package com.Colota.service
import android.app.*
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.IntentFilter
import android.location.Location
+import android.location.LocationManager
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
+import androidx.core.content.ContextCompat
import com.Colota.bridge.LocationServiceModule
import com.Colota.util.AppLogger
import com.Colota.data.DatabaseHelper
@@ -60,6 +65,21 @@ class LocationForegroundService : Service() {
@Volatile private var motionDetector: MotionDetector? = null
@Volatile private var lastKnownLocation: Location? = null
+ /** Debounces the burst of PROVIDERS_CHANGED broadcasts when system Location toggles (one per provider). */
+ @Volatile private var lastBroadcastLocationEnabled: Boolean = true
+
+ private val locationProvidersReceiver = object : BroadcastReceiver() {
+ override fun onReceive(context: Context?, intent: Intent?) {
+ if (intent?.action != LocationManager.PROVIDERS_CHANGED_ACTION) return
+ val current = deviceInfoHelper.isLocationEnabled()
+ if (current == lastBroadcastLocationEnabled) return
+ lastBroadcastLocationEnabled = current
+ AppLogger.d(TAG, "Location providers changed: enabled=$current")
+ LocationServiceModule.sendLocationStateEvent(current)
+ refreshNotificationForCurrentState()
+ }
+ }
+
/** Whether the currently-registered location request bypasses the OS-level distance filter. */
@Volatile private var lastRequestedBypassOsFilter: Boolean = false
@@ -123,6 +143,7 @@ class LocationForegroundService : Service() {
notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
dbHelper = DatabaseHelper.getInstance(this)
deviceInfoHelper = DeviceInfoHelper(this)
+ lastBroadcastLocationEnabled = deviceInfoHelper.isLocationEnabled()
networkManager = NetworkManager(this)
geofenceHelper = GeofenceHelper(this)
secureStorage = SecureStorageHelper.getInstance(this)
@@ -142,9 +163,20 @@ class LocationForegroundService : Service() {
motionDetector = MotionDetector(this) { onMotionDetected() }
+ registerLocationProvidersReceiver()
+
AppLogger.d(TAG, "Service created - provider: ${locationProvider.javaClass.simpleName}, motionSensor=${motionDetector?.isAvailable}")
}
+ private fun registerLocationProvidersReceiver() {
+ val filter = IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION)
+ ContextCompat.registerReceiver(this, locationProvidersReceiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED)
+ }
+
+ private fun unregisterLocationProvidersReceiver() {
+ unregisterReceiver(locationProvidersReceiver)
+ }
+
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (!::dbHelper.isInitialized) {
dbHelper = DatabaseHelper.getInstance(this)
@@ -304,6 +336,7 @@ class LocationForegroundService : Service() {
unregisterWifiPause()
cancelMotionlessCountdown()
cancelHeartbeat()
+ unregisterLocationProvidersReceiver()
conditionMonitor.stop()
stopLocationUpdates()
syncManager.stopPeriodicSync()
@@ -1045,7 +1078,8 @@ class LocationForegroundService : Service() {
isOfflineMode = offline,
isStationary = profileManager.isStationary,
isWifiPaused = isWifiPaused,
- isMotionlessPaused = isMotionlessPaused
+ isMotionlessPaused = isMotionlessPaused,
+ locationEnabled = deviceInfoHelper.isLocationEnabled()
)
}
diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt
index bd29ca16..8d47acc0 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/service/NotificationHelper.kt
@@ -103,8 +103,10 @@ class NotificationHelper(
isOfflineMode: Boolean = false,
isStationary: Boolean = false,
isWifiPaused: Boolean = false,
- isMotionlessPaused: Boolean = false
+ isMotionlessPaused: Boolean = false,
+ locationEnabled: Boolean = true
): String = when {
+ !locationEnabled -> "Location services off - tracking won't get fixes"
isPaused -> {
val zone = zoneName ?: "Unknown"
when {
@@ -166,7 +168,8 @@ class NotificationHelper(
isOfflineMode: Boolean = false,
isStationary: Boolean = false,
isWifiPaused: Boolean = false,
- isMotionlessPaused: Boolean = false
+ isMotionlessPaused: Boolean = false,
+ locationEnabled: Boolean = true
): Boolean {
val now = System.currentTimeMillis()
@@ -191,7 +194,7 @@ class NotificationHelper(
lastCoords = Pair(lat, lon)
}
- val statusText = buildStatusText(isPaused, zoneName, lat, lon, queuedCount, lastSyncTime, isOfflineMode, isStationary, isWifiPaused, isMotionlessPaused)
+ val statusText = buildStatusText(isPaused, zoneName, lat, lon, queuedCount, lastSyncTime, isOfflineMode, isStationary, isWifiPaused, isMotionlessPaused, locationEnabled)
// forceUpdate bypasses dedup so state-change posts land even when the text is unchanged.
val cacheKey = "$statusText-$queuedCount-$activeProfileName"
diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/DeviceInfoHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/util/DeviceInfoHelper.kt
index 74b92417..c9abbb0e 100644
--- a/apps/mobile/android/app/src/main/java/com/colota/util/DeviceInfoHelper.kt
+++ b/apps/mobile/android/app/src/main/java/com/colota/util/DeviceInfoHelper.kt
@@ -7,6 +7,7 @@ package com.Colota.util
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
+import android.location.LocationManager
import android.net.Uri
import android.os.BatteryManager
import android.os.Build
@@ -25,6 +26,10 @@ class DeviceInfoHelper(private val context: Context) {
context.getSystemService(Context.POWER_SERVICE) as PowerManager
}
+ private val locationManager by lazy {
+ context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
+ }
+
private val batteryCache = TimedCache(60000L) { getBatteryStatus() }
companion object {
@@ -97,6 +102,43 @@ class DeviceInfoHelper(private val context: Context) {
return powerManager.isIgnoringBatteryOptimizations(context.packageName)
}
+ /** Whether the system location toggle is on. App permission is separate. */
+ fun isLocationEnabled(): Boolean {
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
+ locationManager.isLocationEnabled
+ } else {
+ @Suppress("DEPRECATION")
+ locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
+ locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
+ }
+ }
+
+ fun openLocationSettings(): Boolean {
+ val candidates = listOf(
+ Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS),
+ Intent(Settings.ACTION_SECURITY_SETTINGS),
+ Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
+ data = Uri.parse("package:${context.packageName}")
+ }
+ )
+ val flags = Intent.FLAG_ACTIVITY_NEW_TASK or
+ Intent.FLAG_ACTIVITY_NO_HISTORY or
+ Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
+ for (intent in candidates) {
+ if (intent.resolveActivity(context.packageManager) == null) continue
+ return try {
+ intent.flags = flags
+ context.startActivity(intent)
+ true
+ } catch (e: Exception) {
+ AppLogger.w(TAG, "Failed to open ${intent.action}, trying next: ${e.message}")
+ continue
+ }
+ }
+ AppLogger.e(TAG, "No supported location settings intent found")
+ return false
+ }
+
fun requestIgnoreBatteryOptimizations(): Boolean {
return try {
val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt
index 4932eddd..6d12c027 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt
@@ -273,6 +273,28 @@ class LocationServiceModuleTest {
assertFalse(LocationServiceModule.sendChargingStateEvent(true))
}
+ // ========================================================================
+ // sendLocationStateEvent
+ // ========================================================================
+
+ @Test
+ fun `sendLocationStateEvent emits onLocationStateChanged when enabled`() {
+ assertTrue(LocationServiceModule.sendLocationStateEvent(true))
+ verify { mockEmitter.emit("onLocationStateChanged", any()) }
+ }
+
+ @Test
+ fun `sendLocationStateEvent emits onLocationStateChanged when disabled`() {
+ assertTrue(LocationServiceModule.sendLocationStateEvent(false))
+ verify { mockEmitter.emit("onLocationStateChanged", any()) }
+ }
+
+ @Test
+ fun `sendLocationStateEvent returns false when no context`() {
+ setCompanionField("reactContextRef", WeakReference<ReactApplicationContext>(null))
+ assertFalse(LocationServiceModule.sendLocationStateEvent(true))
+ }
+
// ========================================================================
// handleChargingChange — invalidates cache and emits event
// ========================================================================
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
index 9a44bc18..62a6ee84 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/LocationForegroundServiceTest.kt
@@ -74,6 +74,7 @@ class LocationForegroundServiceTest {
every { deviceInfoHelper.getCachedBatteryStatus() } returns Pair(80, 2)
every { deviceInfoHelper.isBatteryCritical(any()) } returns false
every { deviceInfoHelper.isBatteryCritical() } returns false
+ every { deviceInfoHelper.isLocationEnabled() } returns true
every { geofenceHelper.getPauseZone(any()) } returns null
mockkObject(PayloadBuilder)
every { PayloadBuilder.buildLocationPayload(any(), any(), any(), any(), any(), any(), any()) } returns JSONObject()
diff --git a/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt
index 7c184f69..55a9613c 100644
--- a/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt
+++ b/apps/mobile/android/app/src/test/java/com/Colota/service/NotificationHelperTest.kt
@@ -106,6 +106,20 @@ class NotificationHelperTest {
)
}
+ @Test
+ fun `status text shows location-off message when location services disabled`() {
+ // Disabled location takes priority over every other state - the user needs to know.
+ assertEquals(
+ "Location services off - tracking won't get fixes",
+ helper.buildStatusText(false, null, 52.0, 13.0, 0, 0L, locationEnabled = false)
+ )
+ // Even when paused or stationary, the location-off message wins.
+ assertEquals(
+ "Location services off - tracking won't get fixes",
+ helper.buildStatusText(true, "Home", 52.0, 13.0, 0, 0L, locationEnabled = false)
+ )
+ }
+
@Test
fun `status text shows coordinates when tracking normally`() {
assertEquals("52.51630, 13.37770", helper.buildStatusText(false, null, 52.51630, 13.37770, 0, 0L))
diff --git a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx b/apps/mobile/src/components/features/dashboard/DashboardMap.tsx
index 8011e47a..5d1d69bf 100644
--- a/apps/mobile/src/components/features/dashboard/DashboardMap.tsx
+++ b/apps/mobile/src/components/features/dashboard/DashboardMap.tsx
@@ -4,7 +4,8 @@
*/
import React, { useRef, useEffect, useMemo, useCallback, useState } from "react"
-import { View, StyleSheet, Text, ActivityIndicator, DeviceEventEmitter, Image } from "react-native"
+import { View, StyleSheet, Text, ActivityIndicator, DeviceEventEmitter, Image, Pressable } from "react-native"
+import { AlertTriangle } from "lucide-react-native"
import { LocationCoords } from "../../../types/global"
import { useTheme } from "../../../hooks/useTheme"
import { useCoords } from "../../../contexts/TrackingProvider"
@@ -28,13 +29,21 @@ type Props = {
pauseReason: string | null
activeProfileName: string | null
isBatteryCritical: boolean
+ locationEnabled: boolean
}
const isValidCoords = (c: LocationCoords | null): c is LocationCoords => {
return c !== null && c.latitude !== 0 && c.longitude !== 0
}
-export function DashboardMap({ tracking, activeZoneName, pauseReason, activeProfileName, isBatteryCritical }: Props) {
+export function DashboardMap({
+ tracking,
+ activeZoneName,
+ pauseReason,
+ activeProfileName,
+ isBatteryCritical,
+ locationEnabled
+}: Props) {
const coords = useCoords()
const mapRef = useRef<ColotaMapRef>(null)
const { colors } = useTheme()
@@ -114,6 +123,8 @@ export function DashboardMap({ tracking, activeZoneName, pauseReason, activeProf
const geofenceData = useMemo(() => buildGeofencesGeoJSON(geofences, colors), [geofences, colors])
const showMap = tracking && isValidCoords(coords)
+ const waitingForFix = tracking && !isValidCoords(coords)
+ const locationOff = tracking && !locationEnabled
return (
<View style={[styles.container, { borderRadius: colors.borderRadius }]}>
@@ -163,7 +174,26 @@ export function DashboardMap({ tracking, activeZoneName, pauseReason, activeProf
</View>
)}
- {tracking && !isValidCoords(coords) && (
+ {waitingForFix && locationOff && (
+ <Pressable
+ onPress={() => NativeLocationService.openLocationSettings()}
+ style={[
+ styles.stateContainer,
+ styles.overlay,
+ { backgroundColor: colors.card, borderRadius: colors.borderRadius }
+ ]}
+ >
+ <View style={[styles.iconCircle, { backgroundColor: colors.warning + "20" }]}>
+ <AlertTriangle size={32} color={colors.warning} />
+ </View>
+ <Text style={[styles.stateTitle, { color: colors.warning }]}>Location Services Off</Text>
+ <Text style={[styles.stateSubtext, { color: colors.textSecondary }]}>
+ Tracking can&apos;t get GPS fixes. Tap to open Settings.
+ </Text>
+ </Pressable>
+ )}
+
+ {waitingForFix && !locationOff && (
<View
style={[
styles.stateContainer,
@@ -191,7 +221,16 @@ export function DashboardMap({ tracking, activeZoneName, pauseReason, activeProf
/>
)}
- {showMap && activeZoneName && (
+ {showMap && locationOff && (
+ <Pressable
+ onPress={() => NativeLocationService.openLocationSettings()}
+ style={[styles.statusBar, { backgroundColor: colors.error + "DD" }]}
+ >
+ <Text style={styles.barText}>Location off - tap to enable</Text>
+ </Pressable>
+ )}
+
+ {showMap && !locationOff && activeZoneName && (
<View style={[styles.statusBar, { backgroundColor: colors.warning + "DD" }]}>
<Text style={styles.barText}>
Paused in {activeZoneName}
@@ -200,7 +239,7 @@ export function DashboardMap({ tracking, activeZoneName, pauseReason, activeProf
</View>
)}
- {showMap && !activeZoneName && activeProfileName && (
+ {showMap && !locationOff && !activeZoneName && activeProfileName && (
<View style={[styles.statusBar, { backgroundColor: colors.primary + "DD" }]}>
<Text style={styles.barText}>{activeProfileName}</Text>
</View>
diff --git a/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx b/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx
index 27144e52..b980e023 100644
--- a/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx
+++ b/apps/mobile/src/components/features/dashboard/__tests__/DashboardMap.test.tsx
@@ -49,7 +49,11 @@ jest.mock("../../../../services/NativeLocationService", () => ({
getSetting: jest.fn().mockResolvedValue(null)
}))
-const mockCoords = { latitude: 48.1, longitude: 11.5, accuracy: 10 }
+let mockCoords: { latitude: number; longitude: number; accuracy: number } | null = {
+ latitude: 48.1,
+ longitude: 11.5,
+ accuracy: 10
+}
jest.mock("../../../../contexts/TrackingProvider", () => ({
useCoords: () => mockCoords
}))
@@ -69,12 +73,17 @@ jest.mock("../../map/MapCenterButton", () => {
import { DashboardMap } from "../DashboardMap"
describe("DashboardMap info cards", () => {
+ beforeEach(() => {
+ mockCoords = { latitude: 48.1, longitude: 11.5, accuracy: 10 }
+ })
+
const baseProps = {
tracking: true,
activeZoneName: null as string | null,
pauseReason: null as string | null,
activeProfileName: null as string | null,
- isBatteryCritical: false
+ isBatteryCritical: false,
+ locationEnabled: true
}
it("shows profile name when activeProfileName is set and no pause zone", () => {
@@ -135,4 +144,45 @@ describe("DashboardMap info cards", () => {
expect(getByText("Tracking Disabled")).toBeTruthy()
expect(getByText("Start tracking to see the map.")).toBeTruthy()
})
+
+ it("shows Location Services Off overlay when tracking but location services are off", () => {
+ mockCoords = null
+ const { getByText, queryByText } = render(<DashboardMap {...baseProps} locationEnabled={false} />)
+
+ expect(getByText("Location Services Off")).toBeTruthy()
+ expect(getByText(/Tap to open Settings/)).toBeTruthy()
+ // The Searching GPS spinner overlay should NOT show simultaneously
+ expect(queryByText("Searching GPS...")).toBeNull()
+ })
+
+ it("shows Searching GPS overlay when tracking and location services are on but no fix yet", () => {
+ mockCoords = null
+ const { getByText, queryByText } = render(<DashboardMap {...baseProps} locationEnabled={true} />)
+
+ expect(getByText("Searching GPS...")).toBeTruthy()
+ expect(queryByText("Location Services Off")).toBeNull()
+ })
+
+ it("shows location-off status bar when tracking with cached coords but location services off", () => {
+ // Coords are valid (cached from before location was disabled), so the full
+ // overlay doesn't fire - the slim status bar at the top of the map does.
+ const { getByText, queryByText } = render(
+ <DashboardMap {...baseProps} activeProfileName="Charging" locationEnabled={false} />
+ )
+
+ expect(getByText("Location off - tap to enable")).toBeTruthy()
+ // Profile chip is hidden while location is off (location-off takes priority)
+ expect(queryByText("Charging")).toBeNull()
+ // Full-screen overlay should NOT show because we have valid coords
+ expect(queryByText("Location Services Off")).toBeNull()
+ })
+
+ it("hides profile and pause-zone chips when location services are off", () => {
+ const { queryByText } = render(
+ <DashboardMap {...baseProps} activeZoneName="Home" activeProfileName="Charging" locationEnabled={false} />
+ )
+
+ expect(queryByText(/Paused in Home/)).toBeNull()
+ expect(queryByText("Charging")).toBeNull()
+ })
})
diff --git a/apps/mobile/src/screens/DashboardScreen.tsx b/apps/mobile/src/screens/DashboardScreen.tsx
index 9c21bda2..1b988685 100644
--- a/apps/mobile/src/screens/DashboardScreen.tsx
+++ b/apps/mobile/src/screens/DashboardScreen.tsx
@@ -4,12 +4,13 @@
*/
import React, { useEffect, useState, useCallback, useRef } from "react"
-import { StyleSheet, View, ScrollView, DeviceEventEmitter, Animated } from "react-native"
+import { StyleSheet, View, ScrollView, DeviceEventEmitter, Animated, AppState } from "react-native"
import { ScreenProps, DatabaseStats } from "../types/global"
import { useTheme } from "../hooks/useTheme"
import NativeLocationService from "../services/NativeLocationService"
import { useTracking } from "../contexts/TrackingProvider"
import { useFocusEffect } from "@react-navigation/native"
+import { showConfirm } from "../services/modalService"
import {
Button,
ConnectionStatus,
@@ -40,11 +41,26 @@ export function DashboardScreen({ navigation }: ScreenProps) {
const [pauseReason, setPauseReason] = useState<string | null>(null)
const [scrollEnabled, setScrollEnabled] = useState(true)
const [isBatteryCritical, setIsBatteryCritical] = useState(false)
+ const [locationEnabled, setLocationEnabled] = useState(true)
// Animation for button
const buttonScale = useRef(new Animated.Value(1)).current
const handleStart = async () => {
+ const locationOn = await NativeLocationService.isLocationEnabled()
+ if (!locationOn) {
+ const openSettings = await showConfirm({
+ title: "Please enable Location Services",
+ message: "Location Services are disabled. Tracking will not work until they are enabled in Settings.",
+ confirmText: "Location Settings",
+ cancelText: "Start Anyway"
+ })
+ if (openSettings) {
+ await NativeLocationService.openLocationSettings()
+ return
+ }
+ }
+
// Bounce animation
Animated.sequence([
Animated.spring(buttonScale, {
@@ -119,6 +135,7 @@ export function DashboardScreen({ navigation }: ScreenProps) {
} else {
setIsBatteryCritical(false)
}
+ NativeLocationService.isLocationEnabled().then(setLocationEnabled)
const interval = tracking ? Math.max(settings.interval * 1000, MIN_STATS_INTERVAL_MS) : STATS_REFRESH_IDLE
@@ -142,6 +159,21 @@ export function DashboardScreen({ navigation }: ScreenProps) {
return () => chargingListener.remove()
}, [])
+ useEffect(() => {
+ const listener = DeviceEventEmitter.addListener("onLocationStateChanged", (data: { locationEnabled: boolean }) => {
+ setLocationEnabled(data.locationEnabled)
+ })
+ const appStateSub = AppState.addEventListener("change", (state) => {
+ if (state === "active") {
+ NativeLocationService.isLocationEnabled().then(setLocationEnabled)
+ }
+ })
+ return () => {
+ listener.remove()
+ appStateSub.remove()
+ }
+ }, [])
+
useEffect(() => {
const pauseZoneListener = DeviceEventEmitter.addListener(
"onPauseZoneChange",
@@ -180,6 +212,7 @@ export function DashboardScreen({ navigation }: ScreenProps) {
pauseReason={pauseReason}
activeProfileName={activeProfileName}
isBatteryCritical={isBatteryCritical}
+ locationEnabled={locationEnabled}
/>
</View>
diff --git a/apps/mobile/src/screens/__tests__/DashboardScreen.test.tsx b/apps/mobile/src/screens/__tests__/DashboardScreen.test.tsx
index 0490136f..c10b45d8 100644
--- a/apps/mobile/src/screens/__tests__/DashboardScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/DashboardScreen.test.tsx
@@ -1,5 +1,5 @@
import React from "react"
-import { render } from "@testing-library/react-native"
+import { render, fireEvent, waitFor } from "@testing-library/react-native"
import { DEFAULT_SETTINGS, Settings } from "../../types/global"
// --- Mocks ---
@@ -7,6 +7,9 @@ import { DEFAULT_SETTINGS, Settings } from "../../types/global"
const mockStartTracking = jest.fn().mockResolvedValue(undefined)
const mockStopTracking = jest.fn().mockResolvedValue(undefined)
const mockSetSettings = jest.fn().mockResolvedValue(undefined)
+const mockIsLocationEnabled = jest.fn().mockResolvedValue(true)
+const mockOpenLocationSettings = jest.fn().mockResolvedValue(true)
+const mockShowConfirm = jest.fn().mockResolvedValue(false)
let mockSettings: Settings = { ...DEFAULT_SETTINGS }
let mockTracking = false
@@ -46,7 +49,11 @@ jest.mock("../../hooks/useTheme", () => ({
}))
jest.mock("@react-navigation/native", () => ({
- useFocusEffect: jest.fn()
+ useFocusEffect: (cb: () => void | (() => void)) => {
+ const { useEffect } = require("react")
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ useEffect(() => cb(), [])
+ }
}))
jest.mock("../../services/NativeLocationService", () => ({
@@ -59,10 +66,17 @@ jest.mock("../../services/NativeLocationService", () => ({
today: 3,
databaseSizeMB: 0.5
}),
- checkCurrentPauseZone: jest.fn().mockResolvedValue(null)
+ checkCurrentPauseZone: jest.fn().mockResolvedValue(null),
+ isBatteryCritical: jest.fn().mockResolvedValue(false),
+ isLocationEnabled: (...args: unknown[]) => mockIsLocationEnabled(...args),
+ openLocationSettings: (...args: unknown[]) => mockOpenLocationSettings(...args)
}
}))
+jest.mock("../../services/modalService", () => ({
+ showConfirm: (...args: unknown[]) => mockShowConfirm(...args)
+}))
+
jest.mock("../../components", () => {
const R = require("react")
const { View, Text, Pressable } = require("react-native")
@@ -88,6 +102,9 @@ describe("DashboardScreen", () => {
mockSettings = { ...DEFAULT_SETTINGS }
mockTracking = false
mockCoords = null
+ mockIsLocationEnabled.mockResolvedValue(true)
+ mockOpenLocationSettings.mockResolvedValue(true)
+ mockShowConfirm.mockResolvedValue(false)
})
it("shows Start Tracking button when not tracking", () => {
@@ -167,4 +184,64 @@ describe("DashboardScreen", () => {
expect(getByTestId("DatabaseStatistics")).toBeTruthy()
})
+
+ // ── Start Tracking + Location Services check (#312) ────────────────────────
+
+ it("starts tracking directly when location services are enabled", async () => {
+ mockTracking = false
+ mockIsLocationEnabled.mockResolvedValue(true)
+
+ const { getByText } = render(<DashboardScreen navigation={mockNavigation} />)
+ fireEvent.press(getByText("Start Tracking"))
+
+ await waitFor(() => expect(mockStartTracking).toHaveBeenCalled())
+ expect(mockShowConfirm).not.toHaveBeenCalled()
+ expect(mockOpenLocationSettings).not.toHaveBeenCalled()
+ })
+
+ it("opens location settings and skips start when user picks 'Location Settings'", async () => {
+ mockTracking = false
+ mockIsLocationEnabled.mockResolvedValue(false)
+ mockShowConfirm.mockResolvedValue(true) // user taps "Location Settings"
+
+ const { getByText } = render(<DashboardScreen navigation={mockNavigation} />)
+ fireEvent.press(getByText("Start Tracking"))
+
+ await waitFor(() => expect(mockOpenLocationSettings).toHaveBeenCalled())
+ expect(mockStartTracking).not.toHaveBeenCalled()
+ })
+
+ it("starts tracking anyway when user dismisses the location warning", async () => {
+ mockTracking = false
+ mockIsLocationEnabled.mockResolvedValue(false)
+ mockShowConfirm.mockResolvedValue(false) // user taps "Close"
+
+ const { getByText } = render(<DashboardScreen navigation={mockNavigation} />)
+ fireEvent.press(getByText("Start Tracking"))
+
+ await waitFor(() => expect(mockStartTracking).toHaveBeenCalled())
+ expect(mockOpenLocationSettings).not.toHaveBeenCalled()
+ })
+
+ it("revalidates locationEnabled when AppState transitions to active", async () => {
+ const { AppState } = require("react-native")
+ const addSpy = jest.spyOn(AppState, "addEventListener")
+
+ render(<DashboardScreen navigation={mockNavigation} />)
+
+ // Wait for the initial isLocationEnabled call from useFocusEffect
+ await waitFor(() => expect(mockIsLocationEnabled).toHaveBeenCalled())
+ const callsAfterMount = mockIsLocationEnabled.mock.calls.length
+
+ const changeHandler = addSpy.mock.calls.find(([event]) => event === "change")?.[1] as (s: string) => void
+ expect(changeHandler).toBeDefined()
+
+ changeHandler("background")
+ expect(mockIsLocationEnabled).toHaveBeenCalledTimes(callsAfterMount)
+
+ changeHandler("active")
+ await waitFor(() => expect(mockIsLocationEnabled).toHaveBeenCalledTimes(callsAfterMount + 1))
+
+ addSpy.mockRestore()
+ })
})
diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.ts
index ed60e9df..22e21b87 100644
--- a/apps/mobile/src/services/NativeLocationService.ts
+++ b/apps/mobile/src/services/NativeLocationService.ts
@@ -594,6 +594,18 @@ class NativeLocationService {
)
}
+ /** Whether the system location toggle is on. App permission is separate. */
+ static async isLocationEnabled(): Promise<boolean> {
+ this.ensureModule()
+ return this.safeExecute(() => LocationServiceModule.isLocationEnabled(), false, "isLocationEnabled failed")
+ }
+
+ /** Opens system Location settings. */
+ static async openLocationSettings(): Promise<boolean> {
+ this.ensureModule()
+ return this.safeExecute(() => LocationServiceModule.openLocationSettings(), false, "openLocationSettings failed")
+ }
+
// ============================================================================
// BUILD CONFIGURATION
// ============================================================================