expo-location-keepalive 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ First version, extracted from a production field-tracking app and tested on TECNO KN8 (HiOS):
6
+
7
+ - Guard service: restores expo-location tracking after swipe / OEM kill and becomes the location foreground service in the background.
8
+ - Native HTTP (`postJson`, `httpPost`) for background location tasks.
9
+ - expo-task-manager TaskService context workaround (`fixTaskService`).
10
+ - Write-ahead offline ping queue (`createOfflineQueue`).
11
+ - Battery / brand auto-start helpers and setup example.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sanket Nehe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,290 @@
1
- # Temporary Holding Version
1
+ # expo-location-keepalive
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p align="center">
4
+ <a href="https://www.npmjs.com/package/expo-location-keepalive"><img src="https://img.shields.io/npm/v/expo-location-keepalive.svg?style=flat-square&color=blue" alt="npm version" /></a>
5
+ <a href="https://www.npmjs.com/package/expo-location-keepalive"><img src="https://img.shields.io/npm/dm/expo-location-keepalive.svg?style=flat-square&color=blue" alt="npm downloads" /></a>
6
+ <a href="https://github.com/Sanketnehe-21/expo-location-keepalive/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green.svg?style=flat-square" alt="license" /></a>
7
+ <a href="https://expo.dev"><img src="https://img.shields.io/badge/Expo-SDK%2052--54%2B-black.svg?style=flat-square" alt="Expo SDK" /></a>
8
+ <img src="https://img.shields.io/badge/platform-Android%20%7C%20iOS%20(safe%20no--op)-lightgrey.svg?style=flat-square" alt="Platform" />
9
+ </p>
10
+
11
+ Keeps **`expo-location`** background tracking alive on Android when the user swipes the app away from recent apps, or when aggressive OEM battery managers (**Xiaomi**, **Oppo**, **Vivo**, **TECNO**, **Samsung**, etc.) kill the process.
12
+
13
+ > **Platform Support**: **Android**. On iOS, every function is a safe no-op.
14
+
15
+ ---
16
+
17
+ ## ⚡ The Problem
18
+
19
+ On standard Android devices from OEMs with aggressive power managers, background location in React Native and Expo often fails in production:
20
+
21
+ * ❌ **Swiped app stops tracking:** Swiping the app from recent apps immediately terminates the process, even with a foreground service running.
22
+ * ❌ **Headless fetch hang:** After Android restores the app in the background, React Native's JS `fetch()` requests stall indefinitely without firing JS callbacks, causing Android to kill the task after 2.5 minutes.
23
+ * ❌ **TaskService context crash:** `expo-task-manager` references a stale React context from headless boot, throwing `SharedPreferences.getAll() on a null object` and permanently breaking start/stop calls.
24
+ * ❌ **Expo foreground service lockout:** `expo-location` refuses to start its own foreground service without an active screen/Activity, causing Android to throttle fixes to once every few hours.
25
+ * ❌ **Delayed/lost alarms:** OEM "proxy alarms" hold back or swallow scheduled `AlarmManager` alarms.
26
+
27
+ ### 🏆 Benchmark Results
28
+
29
+ Tested on a **TECNO KN8 (HiOS)** — known as one of the most aggressive OEM task killers on Android:
30
+ * After a user swipe, the tracking process was restored in **0.26 seconds**.
31
+ * Delivered **121 consecutive location pings over 10 minutes** (5s interval, max gap 8s).
32
+ * **0 crashes**, with the UI never reopened.
33
+
34
+ ---
35
+
36
+ ## 📦 Installation
37
+
38
+ ```bash
39
+ # Install peer dependencies
40
+ npx expo install expo-location expo-task-manager @react-native-async-storage/async-storage
41
+
42
+ # Install expo-location-keepalive
43
+ npm install expo-location-keepalive
44
+ ```
45
+
46
+ > **Note:** Requires a Development Build or EAS Build (`npx expo prebuild` / `eas build`). Native code cannot run inside standard Expo Go.
47
+
48
+ ### Configure `app.json`
49
+
50
+ Add the `expo-location` plugin configuration to your `app.json`:
51
+
52
+ ```json
53
+ {
54
+ "expo": {
55
+ "plugins": [
56
+ [
57
+ "expo-location",
58
+ {
59
+ "isAndroidBackgroundLocationEnabled": true,
60
+ "isAndroidForegroundServiceEnabled": true
61
+ }
62
+ ]
63
+ ]
64
+ }
65
+ }
66
+ ```
67
+
68
+ The native permissions and service declarations for `expo-location-keepalive` are **automatically linked and merged** into your `AndroidManifest.xml` during prebuild.
69
+
70
+ ---
71
+
72
+ ## 🚀 Quick Start
73
+
74
+ ### 1. Define Background Task (Entry Point)
75
+
76
+ Define your task at the **top level** of your entry file (e.g., `index.js` or `App.js`).
77
+
78
+ ```js
79
+ import * as Location from 'expo-location'
80
+ import * as TaskManager from 'expo-task-manager'
81
+ import AsyncStorage from '@react-native-async-storage/async-storage'
82
+ import {
83
+ startGuard,
84
+ stopGuard,
85
+ demoteGuard,
86
+ fixTaskService,
87
+ postJson,
88
+ createOfflineQueue,
89
+ } from 'expo-location-keepalive'
90
+
91
+ const API_ENDPOINT = 'https://api.yourdomain.com/locations'
92
+ const LOCATION_TASK = 'BACKGROUND_LOCATION_TASK'
93
+
94
+ // 1. Create offline queue to ensure 0 lost pings
95
+ const queue = createOfflineQueue({
96
+ storage: AsyncStorage,
97
+ batchUrl: `${API_ENDPOINT}/batch`,
98
+ getHeaders: async () => {
99
+ const token = await AsyncStorage.getItem('user_token')
100
+ return token ? { Authorization: `Bearer ${token}` } : {}
101
+ },
102
+ })
103
+
104
+ // 2. Define background task at the top level
105
+ TaskManager.defineTask(LOCATION_TASK, async ({ data, error }) => {
106
+ if (error || !data?.locations?.length) return
107
+
108
+ // Cheap to call; keeps the guard armed on every location fix
109
+ startGuard()
110
+
111
+ const fix = data.locations[data.locations.length - 1]
112
+ const ping = {
113
+ latitude: fix.coords.latitude,
114
+ longitude: fix.coords.longitude,
115
+ accuracy: fix.coords.accuracy,
116
+ timestamp: new Date(fix.timestamp).toISOString(),
117
+ }
118
+
119
+ // Save to persistent storage first (Write-Ahead)
120
+ const id = await queue.enqueue(ping)
121
+
122
+ try {
123
+ const token = await AsyncStorage.getItem('user_token')
124
+ const headers = token ? { Authorization: `Bearer ${token}` } : {}
125
+
126
+ // Use postJson (native HTTP), NOT fetch!
127
+ const status = await postJson(API_ENDPOINT, headers, ping)
128
+
129
+ if (status >= 200 && status < 300) {
130
+ await queue.ack(id)
131
+ await queue.flush()
132
+ }
133
+ } catch (err) {
134
+ // Ping stays queued in AsyncStorage and flushes on next connection
135
+ }
136
+ })
137
+ ```
138
+
139
+ ### 2. Start & Stop Tracking
140
+
141
+ ```js
142
+ export async function startTracking() {
143
+ // Apply TaskService patch before starting
144
+ fixTaskService()
145
+
146
+ const isRunning = await Location.hasStartedLocationUpdatesAsync(LOCATION_TASK).catch(() => false)
147
+ if (isRunning) await Location.stopLocationUpdatesAsync(LOCATION_TASK)
148
+
149
+ await Location.startLocationUpdatesAsync(LOCATION_TASK, {
150
+ accuracy: Location.Accuracy.High,
151
+ timeInterval: 5000,
152
+ distanceInterval: 0,
153
+ pausesUpdatesAutomatically: false,
154
+ foregroundService: {
155
+ notificationTitle: 'Live Tracking Active',
156
+ notificationBody: 'Transmitting location in the background.',
157
+ },
158
+ })
159
+
160
+ // Start native guard
161
+ startGuard({
162
+ notificationTitle: 'Live Tracking Active',
163
+ notificationBody: 'Tracking remains active.',
164
+ })
165
+
166
+ // Demote guard's notification while the app screen is visible
167
+ demoteGuard()
168
+ }
169
+
170
+ export async function stopTracking() {
171
+ fixTaskService()
172
+
173
+ const isRunning = await Location.hasStartedLocationUpdatesAsync(LOCATION_TASK).catch(() => false)
174
+ if (isRunning) await Location.stopLocationUpdatesAsync(LOCATION_TASK)
175
+
176
+ stopGuard()
177
+ await queue.clear()
178
+ }
179
+ ```
180
+
181
+ ---
182
+
183
+ ## ⚠️ The 5 Golden Rules of Android Background Tracking
184
+
185
+ 1. **Top-Level `defineTask`**: Always declare `TaskManager.defineTask` at module top-level, imported directly in your application entry file.
186
+ 2. **Stateless Headless Execution**: The background task must read authentication tokens, IDs, and configurations from persistent storage (`AsyncStorage`). When restarted headlessly, there is **no UI and no React state**.
187
+ 3. **Always Use `postJson` (Native HTTP)**: Never use standard `fetch` inside the background location task. On headless Android wakeups, JS `fetch` promises fail to resolve.
188
+ 4. **Never Stop Tracking in Component Unmount**: Do not call `stopLocationUpdatesAsync` inside `useEffect` return cleanups. Swiping the app destroys the activity and unmounts components. Call `stopTracking()` **only on explicit user logout or action**.
189
+ 5. **Enforce Battery Exemption**: The app **must** have its battery set to *"Unrestricted"*. Restrictive battery settings block background network and process restarts.
190
+
191
+ ---
192
+
193
+ ## 🛠️ Complete API Reference
194
+
195
+ ### Guard Management
196
+
197
+ #### `startGuard(options?)`
198
+ Starts or maintains the native guard service. Safe and cheap to call repeatedly inside the location task.
199
+ * `options.notificationTitle` *(string)*: Notification title displayed when the app is restored headlessly.
200
+ * `options.notificationBody` *(string)*: Notification body text.
201
+ * `options.channelName` *(string)*: Notification channel name displayed in Android System Settings.
202
+
203
+ #### `stopGuard()`
204
+ Terminates the native guard service. Call this together with `Location.stopLocationUpdatesAsync` (e.g. on user logout).
205
+
206
+ #### `demoteGuard()`
207
+ Hides the guard service's persistent notification once the app screen is visible again, avoiding duplicate notifications alongside Expo's foreground service.
208
+
209
+ #### `fixTaskService()`
210
+ Applies a reflection patch to `expo-task-manager`, repointing `TaskService.mContextRef` to the persistent `applicationContext` to prevent `SharedPreferences.getAll() on a null object` crashes.
211
+
212
+ ---
213
+
214
+ ### Networking & Queueing
215
+
216
+ #### `postJson(url, headers?, body?, timeoutMs?): Promise<number>`
217
+ Native HTTP POST (`HttpURLConnection`) with a fallback to `fetch`. Resolves to the HTTP status code (e.g. `200`). Bypasses React Native's background networking thread freeze.
218
+
219
+ #### `httpPost(url, headers?, body?, timeoutMs?): Promise<number | null>`
220
+ Direct native HTTP POST without `fetch` fallback. Returns `null` if the native module is unavailable.
221
+
222
+ #### `createOfflineQueue(options): OfflineQueue`
223
+ Instantiates a write-ahead persistent location queue backed by `AsyncStorage`.
224
+ * `options.storage`: AsyncStorage-compatible storage interface (`getItem`, `setItem`, `removeItem`).
225
+ * `options.batchUrl`: API endpoint accepting `{ pings: [...] }`.
226
+ * `options.getHeaders`: Function returning request headers (e.g., auth tokens).
227
+ * `options.maxItems` *(optional, default 1500)*: Max items retained in queue.
228
+ * `options.maxAgeMs` *(optional, default 24h)*: Max age before an un-sent ping expires.
229
+ * `options.chunkSize` *(optional, default 200)*: Pings per batch upload request.
230
+
231
+ Methods:
232
+ * `enqueue(ping)`: Saves ping to storage. Returns ping ID.
233
+ * `ack(id)`: Acknowledges server delivery and removes ping from storage.
234
+ * `flush()`: Delivers all pending pings in chunks to the batch endpoint.
235
+ * `size()`: Returns total pending pings.
236
+ * `clear()`: Flushes pending pings (best-effort) and clears storage on logout.
237
+
238
+ ---
239
+
240
+ ### OEM Battery & Autostart Helpers
241
+
242
+ | Function | Returns | Description |
243
+ |---|---|---|
244
+ | `isBatteryUnrestricted()` | `boolean` | Returns `true` if the app is exempt from Android battery optimization (always `true` on iOS). |
245
+ | `requestBatteryUnrestricted()` | `boolean` | Launches Android's native system dialog requesting battery optimization exemption. |
246
+ | `openAutoStartSettings()` | `boolean` | Opens brand-specific autostart settings for Xiaomi, Oppo, Vivo, TECNO, Samsung. |
247
+ | `brandStep(appName?)` | `BrandStep \| null` | Returns `{ brand, text }` instructions tailored to the device manufacturer, or `null` if stock Android. |
248
+
249
+ ---
250
+
251
+ ## 📱 OEM Autostart Permission Gate Example
252
+
253
+ Use the ready-made setup screen component to ensure the user grants required permissions before starting tracking:
254
+
255
+ * Setup Screen Code: [`example/SetupScreen.js`](example/SetupScreen.js)
256
+ * Complete Tracking Integration: [`example/tracking.js`](example/tracking.js)
257
+
258
+ ---
259
+
260
+ ## 🔍 Diagnostics & Testing
261
+
262
+ Monitor background lifecycle transitions and guard activations via `adb logcat`:
263
+
264
+ ```bash
265
+ adb logcat -v time | grep -E "LocKeepAlive|has died|removeTask"
266
+ ```
267
+
268
+ Expected trace when an app is swiped away:
269
+ ```text
270
+ ActivityManager: Process <package.name> (pid 12345) has died <-- Swiped / OEM Kill
271
+ LocKeepAlive: guard-created <-- Guard recreated
272
+ LocKeepAlive: wake reason=guard-created <-- Waking Expo TaskManager
273
+ LocKeepAlive: guard-foreground <-- Elevated to location FG service
274
+ LocKeepAlive: taskservice-context-fixed <-- Patch applied
275
+ ```
276
+
277
+ Refer to [`docs/TESTING.md`](docs/TESTING.md) for detailed real-device testing procedures.
278
+
279
+ ---
280
+
281
+ ## 📄 Google Play Store Guidelines
282
+
283
+ * `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS`: Permitted by Google Play for apps whose core function requires continuous background tracking (e.g. delivery, transport, safety, field workforce).
284
+ * `FOREGROUND_SERVICE_LOCATION`: Google Play requires a prominent in-app disclosure and declaration when submitting your app bundle.
285
+
286
+ ---
287
+
288
+ ## 📄 License
289
+
290
+ MIT © [Sanket Nehe](https://github.com/Sanketnehe-21)
@@ -0,0 +1,16 @@
1
+ plugins {
2
+ id 'com.android.library'
3
+ id 'expo-module-gradle-plugin'
4
+ }
5
+
6
+ group = 'expo.modules.locationkeepalive'
7
+ version = '0.1.0'
8
+
9
+ android {
10
+ namespace "expo.modules.locationkeepalive"
11
+ defaultConfig {
12
+ versionCode 1
13
+ versionName '0.1.0'
14
+ consumerProguardFiles 'proguard-rules.pro'
15
+ }
16
+ }
@@ -0,0 +1,3 @@
1
+ # TaskServiceContextFix reaches these expo-task-manager fields by name
2
+ -keepclassmembers class expo.modules.taskManager.TaskManagerPackage { static ** mTaskService; }
3
+ -keepclassmembers class expo.modules.taskManager.TaskService { ** mContextRef; }
@@ -0,0 +1,21 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
3
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
4
+ <!-- Shows Android's own "allow background" dialog (requestBatteryUnrestricted).
5
+ Google Play requires a declaration for this permission — see README. -->
6
+ <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
7
+
8
+ <application>
9
+ <!-- Watches tracking; restarted by Android after an OEM kill, restores
10
+ tracking, and becomes the location foreground service in the background. -->
11
+ <service
12
+ android:name="expo.modules.locationkeepalive.KeepAliveGuardService"
13
+ android:exported="false"
14
+ android:foregroundServiceType="location"
15
+ android:stopWithTask="false" />
16
+
17
+ <receiver
18
+ android:name="expo.modules.locationkeepalive.KeepAliveWakeReceiver"
19
+ android:exported="false" />
20
+ </application>
21
+ </manifest>
@@ -0,0 +1,25 @@
1
+ package expo.modules.locationkeepalive
2
+
3
+ import android.content.Context
4
+
5
+ // Settings the native side needs AFTER the app process was killed and restarted
6
+ // in the background — JS isn't running then, so they are stored on disk when JS
7
+ // calls startGuard().
8
+ internal object KeepAliveConfig {
9
+ const val TAG = "LocKeepAlive"
10
+ private const val PREFS = "expo_location_keepalive"
11
+
12
+ private fun prefs(ctx: Context) = ctx.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
13
+
14
+ fun save(ctx: Context, title: String?, body: String?, channelName: String?) {
15
+ prefs(ctx).edit()
16
+ .putString("title", title)
17
+ .putString("body", body)
18
+ .putString("channelName", channelName)
19
+ .apply()
20
+ }
21
+
22
+ fun title(ctx: Context): String = prefs(ctx).getString("title", null) ?: "Location tracking"
23
+ fun body(ctx: Context): String = prefs(ctx).getString("body", null) ?: "Sharing your live location"
24
+ fun channelName(ctx: Context): String = prefs(ctx).getString("channelName", null) ?: "Location tracking"
25
+ }
@@ -0,0 +1,149 @@
1
+ package expo.modules.locationkeepalive
2
+
3
+ import android.app.Notification
4
+ import android.app.NotificationChannel
5
+ import android.app.NotificationManager
6
+ import android.app.PendingIntent
7
+ import android.app.Service
8
+ import android.content.Context
9
+ import android.content.Intent
10
+ import android.content.pm.ServiceInfo
11
+ import android.os.Build
12
+ import android.os.IBinder
13
+ import android.os.PowerManager
14
+ import android.util.Log
15
+
16
+ // Runs while location tracking is on.
17
+ // - Plain service while the app is open: expo-location's own foreground
18
+ // service keeps the app alive and this one just watches.
19
+ // - onTaskRemoved: the user swiped the app away → arm a backup restart alarm.
20
+ // - Recreated by Android after an OEM kill (START_STICKY) → restore tracking
21
+ // straight from onCreate (OEM power managers often hold back alarms).
22
+ // - After a background restore it becomes the "location" foreground service
23
+ // itself: expo-location refuses to start one without a visible screen, and
24
+ // without one Android throttles location to a few fixes an hour.
25
+ class KeepAliveGuardService : Service() {
26
+ override fun onBind(intent: Intent?): IBinder? = null
27
+
28
+ override fun onCreate() {
29
+ super.onCreate()
30
+ running = true
31
+ instance = this
32
+ Log.i(KeepAliveConfig.TAG, "guard-created")
33
+ // Harmless when the app is already tracking — the restore is a no-op then.
34
+ KeepAliveWake.kick(this, "guard-created")
35
+ }
36
+
37
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
38
+ val foreground = intent?.getBooleanExtra(EXTRA_FOREGROUND, false) == true
39
+ // intent == null means Android restarted us after killing the process
40
+ Log.i(KeepAliveConfig.TAG, "guard-start sticky=${intent == null} fg=$foreground")
41
+ if (foreground) goForeground()
42
+ if (intent == null) KeepAliveWake.kick(this, "sticky-restart")
43
+ return START_STICKY
44
+ }
45
+
46
+ override fun onTaskRemoved(rootIntent: Intent?) {
47
+ Log.i(KeepAliveConfig.TAG, "task-removed")
48
+ // Backup for phones that kill the process a moment later
49
+ KeepAliveWake.scheduleRestart(this, 3_000)
50
+ super.onTaskRemoved(rootIntent)
51
+ }
52
+
53
+ override fun onDestroy() {
54
+ Log.i(KeepAliveConfig.TAG, "guard-destroyed")
55
+ running = false
56
+ if (instance === this) instance = null
57
+ super.onDestroy()
58
+ }
59
+
60
+ private fun goForeground() {
61
+ try {
62
+ val nm = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
63
+ if (nm.getNotificationChannel(CHANNEL_ID) == null) {
64
+ nm.createNotificationChannel(
65
+ NotificationChannel(CHANNEL_ID, KeepAliveConfig.channelName(this), NotificationManager.IMPORTANCE_LOW)
66
+ )
67
+ }
68
+ val open = packageManager.getLaunchIntentForPackage(packageName)?.let {
69
+ PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
70
+ }
71
+ val notification = Notification.Builder(this, CHANNEL_ID)
72
+ .setContentTitle(KeepAliveConfig.title(this))
73
+ .setContentText(KeepAliveConfig.body(this))
74
+ .setSmallIcon(applicationInfo.icon)
75
+ .setOngoing(true)
76
+ .setContentIntent(open)
77
+ .setCategory(Notification.CATEGORY_SERVICE)
78
+ .build()
79
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
80
+ startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION)
81
+ } else {
82
+ startForeground(NOTIFICATION_ID, notification)
83
+ }
84
+ Log.i(KeepAliveConfig.TAG, "guard-foreground")
85
+ } catch (e: Exception) {
86
+ // Started with startForegroundService(): if startForeground() can't be
87
+ // called, Android crashes the app 30 s later. Stop instead.
88
+ Log.w(KeepAliveConfig.TAG, "guard-foreground-failed: ${e.message}")
89
+ stopSelf()
90
+ }
91
+ }
92
+
93
+ companion object {
94
+ private const val CHANNEL_ID = "expo-location-keepalive"
95
+ private const val NOTIFICATION_ID = 481757
96
+ private const val EXTRA_FOREGROUND = "foreground"
97
+
98
+ @Volatile var running = false
99
+ @Volatile private var instance: KeepAliveGuardService? = null
100
+
101
+ // Set by LocationKeepAliveModule from the activity lifecycle. A process
102
+ // Android restored in the background never shows the screen, so this stays
103
+ // false. (Process "importance" can't be used: Android reports foreground
104
+ // while it is still starting this service.)
105
+ @Volatile var appVisible = false
106
+
107
+ fun ensureRunning(context: Context) {
108
+ if (running) return
109
+ try {
110
+ context.startService(Intent(context, KeepAliveGuardService::class.java))
111
+ } catch (e: Exception) {
112
+ // Background start refused — the next JS start/fix call will retry
113
+ Log.w(KeepAliveConfig.TAG, "guard-start-refused: ${e.message}")
114
+ }
115
+ }
116
+
117
+ // True when the screen isn't showing (restored in the background) and
118
+ // Android will let us start a foreground service: battery "unrestricted"
119
+ // is what exempts the app from the background-start ban.
120
+ fun needsForeground(context: Context): Boolean {
121
+ if (appVisible) return false
122
+ val pm = context.getSystemService(Context.POWER_SERVICE) as? PowerManager
123
+ return pm?.isIgnoringBatteryOptimizations(context.packageName) == true
124
+ }
125
+
126
+ fun startForeground(context: Context) {
127
+ try {
128
+ context.startForegroundService(
129
+ Intent(context, KeepAliveGuardService::class.java).putExtra(EXTRA_FOREGROUND, true)
130
+ )
131
+ } catch (e: Exception) {
132
+ Log.w(KeepAliveConfig.TAG, "guard-foreground-refused: ${e.message}")
133
+ }
134
+ }
135
+
136
+ // The app screen started tracking again (expo's notification is back) —
137
+ // drop ours so the user doesn't see two.
138
+ fun demote() {
139
+ instance?.let {
140
+ it.stopForeground(STOP_FOREGROUND_REMOVE)
141
+ Log.i(KeepAliveConfig.TAG, "guard-demoted")
142
+ }
143
+ }
144
+
145
+ fun stop(context: Context) {
146
+ context.stopService(Intent(context, KeepAliveGuardService::class.java))
147
+ }
148
+ }
149
+ }
@@ -0,0 +1,50 @@
1
+ package expo.modules.locationkeepalive
2
+
3
+ import android.app.AlarmManager
4
+ import android.app.PendingIntent
5
+ import android.content.Context
6
+ import android.content.Intent
7
+ import android.os.SystemClock
8
+ import android.util.Log
9
+
10
+ // Brings background tracking back after the app process was killed.
11
+ //
12
+ // Tracking itself is expo-location's: its task is persisted by
13
+ // expo-task-manager, and a fresh process restores it (location updates) as soon
14
+ // as a TaskService is created. TaskBroadcastReceiver creates one on ANY
15
+ // broadcast, so "restart tracking" is just waking that receiver. If JS stopped
16
+ // tracking (stopLocationUpdatesAsync), nothing is persisted and this is a no-op.
17
+ internal object KeepAliveWake {
18
+ const val ACTION_WAKE = "expo.modules.locationkeepalive.WAKE"
19
+ private const val EXPO_TASK_RECEIVER = "expo.modules.taskManager.TaskBroadcastReceiver"
20
+
21
+ fun kick(context: Context, reason: String) {
22
+ val ctx = context.applicationContext
23
+ Log.i(KeepAliveConfig.TAG, "wake reason=$reason")
24
+ TaskServiceContextFix.apply(ctx)
25
+ try {
26
+ ctx.sendBroadcast(Intent(ACTION_WAKE).setClassName(ctx.packageName, EXPO_TASK_RECEIVER))
27
+ } catch (e: Exception) {
28
+ Log.w(KeepAliveConfig.TAG, "wake failed: ${e.message}")
29
+ }
30
+ // Restored in the background (no screen): expo-location refuses to start
31
+ // its own foreground service there. The guard becomes the location
32
+ // foreground service instead, so fixes keep arriving at full rate.
33
+ if (KeepAliveGuardService.needsForeground(ctx)) KeepAliveGuardService.startForeground(ctx)
34
+ else if (reason != "guard-created") KeepAliveGuardService.ensureRunning(ctx)
35
+ }
36
+
37
+ // Inexact on purpose: needs no exact-alarm permission. Only a backup to the
38
+ // guard restart — OEM power managers (e.g. TECNO "proxy alarm") may delay it.
39
+ fun scheduleRestart(context: Context, delayMs: Long) {
40
+ val ctx = context.applicationContext
41
+ val alarm = ctx.getSystemService(Context.ALARM_SERVICE) as? AlarmManager ?: return
42
+ val pi = PendingIntent.getBroadcast(
43
+ ctx, 0,
44
+ Intent(ctx, KeepAliveWakeReceiver::class.java).setAction(ACTION_WAKE),
45
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
46
+ )
47
+ alarm.setAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + delayMs, pi)
48
+ Log.i(KeepAliveConfig.TAG, "restart-armed inMs=$delayMs")
49
+ }
50
+ }
@@ -0,0 +1,12 @@
1
+ package expo.modules.locationkeepalive
2
+
3
+ import android.content.BroadcastReceiver
4
+ import android.content.Context
5
+ import android.content.Intent
6
+
7
+ // Target of the backup restart alarm armed when the app is swiped away.
8
+ class KeepAliveWakeReceiver : BroadcastReceiver() {
9
+ override fun onReceive(context: Context, intent: Intent) {
10
+ KeepAliveWake.kick(context, "swipe-alarm")
11
+ }
12
+ }
@@ -0,0 +1,118 @@
1
+ package expo.modules.locationkeepalive
2
+
3
+ import android.content.ComponentName
4
+ import android.content.Context
5
+ import android.content.Intent
6
+ import android.net.Uri
7
+ import android.os.Build
8
+ import android.os.PowerManager
9
+ import android.provider.Settings
10
+ import expo.modules.kotlin.modules.Module
11
+ import expo.modules.kotlin.modules.ModuleDefinition
12
+ import java.net.HttpURLConnection
13
+ import java.net.URL
14
+
15
+ class LocationKeepAliveModule : Module() {
16
+ private val context: Context
17
+ get() = appContext.reactContext ?: throw IllegalStateException("No React context")
18
+
19
+ override fun definition() = ModuleDefinition {
20
+ Name("LocationKeepAlive")
21
+
22
+ // Runs for every React context (app screen and background/headless alike),
23
+ // before JS can call into expo-location.
24
+ OnCreate { TaskServiceContextFix.apply(context) }
25
+
26
+ OnActivityEntersForeground { KeepAliveGuardService.appVisible = true }
27
+ OnActivityEntersBackground { KeepAliveGuardService.appVisible = false }
28
+
29
+ Constant("manufacturer") { Build.MANUFACTURER.lowercase() }
30
+
31
+ // Call right after Location.startLocationUpdatesAsync (and cheaply on every
32
+ // fix) so the guard is in place to catch a swipe-away / OEM kill.
33
+ Function("startGuard") { title: String?, body: String?, channelName: String? ->
34
+ KeepAliveConfig.save(context, title, body, channelName)
35
+ KeepAliveGuardService.ensureRunning(context)
36
+ }
37
+
38
+ Function("stopGuard") { KeepAliveGuardService.stop(context) }
39
+
40
+ // App screen started tracking again (expo's notification is back)
41
+ Function("demoteGuard") { KeepAliveGuardService.demote() }
42
+
43
+ // Call just before start/stopLocationUpdatesAsync
44
+ Function("fixTaskService") { TaskServiceContextFix.apply(context) }
45
+
46
+ // HTTP POST done natively. When Android restarts the app in the background
47
+ // (no screen), React Native's fetch sends the request but its response never
48
+ // reaches JS: the task never finishes, and after a few minutes Android stops
49
+ // running it. Promises from native modules still resolve there.
50
+ // Returns the HTTP status; throws on a network error. Runs off the main thread.
51
+ AsyncFunction("httpPost") { url: String, headers: Map<String, String>, body: String, timeoutMs: Int ->
52
+ val conn = URL(url).openConnection() as HttpURLConnection
53
+ try {
54
+ conn.requestMethod = "POST"
55
+ conn.connectTimeout = timeoutMs
56
+ conn.readTimeout = timeoutMs
57
+ conn.doOutput = true
58
+ conn.setRequestProperty("Content-Type", "application/json")
59
+ headers.forEach { (k, v) -> conn.setRequestProperty(k, v) }
60
+ conn.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) }
61
+ val status = conn.responseCode
62
+ // Drain the body so the connection can be reused
63
+ (if (status >= 400) conn.errorStream else conn.inputStream)?.use { it.readBytes() }
64
+ status
65
+ } finally {
66
+ conn.disconnect()
67
+ }
68
+ }
69
+
70
+ Function("isIgnoringBatteryOptimizations") {
71
+ val pm = context.getSystemService(Context.POWER_SERVICE) as? PowerManager
72
+ pm?.isIgnoringBatteryOptimizations(context.packageName) == true
73
+ }
74
+
75
+ // Android's own "Let app always run in background?" dialog; falls back to
76
+ // the battery list if a vendor build blocks the dialog.
77
+ Function("requestIgnoreBatteryOptimizations") {
78
+ val direct = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, Uri.parse("package:${context.packageName}"))
79
+ launch(direct) || launch(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS))
80
+ }
81
+
82
+ // Brand auto-start / "never sleeping" screen. Returns false when none of the
83
+ // known screens exist; the app-info page is opened instead.
84
+ Function("openAutoStartSettings") {
85
+ AUTOSTART_SCREENS.any { (pkg, cls) -> launch(Intent().setComponent(ComponentName(pkg, cls))) } ||
86
+ !launch(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}")))
87
+ }
88
+ }
89
+
90
+ private fun launch(intent: Intent): Boolean = try {
91
+ context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
92
+ true
93
+ } catch (e: Exception) {
94
+ false
95
+ }
96
+
97
+ companion object {
98
+ // Tried in order; the first one present on the phone opens.
99
+ private val AUTOSTART_SCREENS = listOf(
100
+ // Xiaomi / Redmi / POCO
101
+ "com.miui.securitycenter" to "com.miui.permcenter.autostart.AutoStartManagementActivity",
102
+ // Oppo / Realme / OnePlus (ColorOS)
103
+ "com.coloros.safecenter" to "com.coloros.safecenter.permission.startup.StartupAppListActivity",
104
+ "com.coloros.safecenter" to "com.coloros.safecenter.startupapp.StartupAppListActivity",
105
+ "com.oplus.safecenter" to "com.oplus.safecenter.permission.startup.StartupAppListActivity",
106
+ "com.oppo.safe" to "com.oppo.safe.permission.startup.StartupAppListActivity",
107
+ // Vivo / iQOO
108
+ "com.vivo.permissionmanager" to "com.vivo.permissionmanager.activity.BgStartUpManagerActivity",
109
+ "com.iqoo.secure" to "com.iqoo.secure.ui.phoneoptimize.BgStartUpManager",
110
+ // TECNO / Infinix / itel (Transsion "Phone Master")
111
+ "com.transsion.phonemaster" to "com.cyin.himgr.autostart.AutoStartActivity",
112
+ "com.transsion.phonemanager" to "com.itel.autobootmanager.activity.AutoBootMgrActivity",
113
+ // Samsung — battery page holding "Never sleeping apps"
114
+ "com.samsung.android.lool" to "com.samsung.android.sm.battery.ui.BatteryActivity",
115
+ "com.samsung.android.lool" to "com.samsung.android.sm.ui.battery.BatteryActivity",
116
+ )
117
+ }
118
+ }
@@ -0,0 +1,35 @@
1
+ package expo.modules.locationkeepalive
2
+
3
+ import android.content.Context
4
+ import android.util.Log
5
+ import java.lang.ref.WeakReference
6
+
7
+ // Works around an expo-task-manager bug that background restarts expose.
8
+ //
9
+ // TaskManagerPackage keeps ONE TaskService per process, holding a WeakReference
10
+ // to whichever React context created it first. When Android starts the app in
11
+ // the background (no screen), that is the headless context; once it is
12
+ // discarded the reference is cleared, and every later start/stop of location
13
+ // updates fails with "SharedPreferences.getAll() on a null object" — tracking
14
+ // can't be (re)started even after the user opens the app. All other TaskService
15
+ // state is static, so pointing it at the application context is safe.
16
+ internal object TaskServiceContextFix {
17
+ fun apply(context: Context) {
18
+ try {
19
+ val appContext = context.applicationContext
20
+ val holder = Class.forName("expo.modules.taskManager.TaskManagerPackage").getDeclaredField("mTaskService")
21
+ holder.isAccessible = true
22
+ val service = holder.get(null) ?: return
23
+
24
+ val ref = service.javaClass.getDeclaredField("mContextRef")
25
+ ref.isAccessible = true
26
+ val current = (ref.get(service) as? WeakReference<*>)?.get()
27
+ if (current !== appContext) {
28
+ ref.set(service, WeakReference<Context>(appContext))
29
+ Log.i(KeepAliveConfig.TAG, "taskservice-context-fixed wasNull=${current == null}")
30
+ }
31
+ } catch (e: Exception) {
32
+ Log.w(KeepAliveConfig.TAG, "taskservice-fix-failed: ${e.message}")
33
+ }
34
+ }
35
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "platforms": ["android"],
3
+ "android": {
4
+ "modules": ["expo.modules.locationkeepalive.LocationKeepAliveModule"]
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "expo-location-keepalive",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Keeps expo-location background tracking alive on Android after the app is swiped away or killed by OEM battery managers (Xiaomi, Oppo, Vivo, TECNO, Samsung).",
5
+ "main": "src/index.js",
6
+ "types": "src/index.d.ts",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/Sanketnehe-21/expo-location-keepalive.git"
10
+ },
11
+ "homepage": "https://github.com/Sanketnehe-21/expo-location-keepalive#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/Sanketnehe-21/expo-location-keepalive/issues"
14
+ },
15
+ "author": "Sanket Nehe",
16
+ "files": [
17
+ "src",
18
+ "android",
19
+ "expo-module.config.json",
20
+ "README.md",
21
+ "LICENSE",
22
+ "CHANGELOG.md"
23
+ ],
24
+ "keywords": [
25
+ "expo",
26
+ "react-native",
27
+ "expo-location",
28
+ "background-location",
29
+ "foreground-service",
30
+ "android",
31
+ "keep-alive",
32
+ "expo-task-manager"
33
+ ],
34
+ "license": "MIT",
35
+ "peerDependencies": {
36
+ "expo": ">=54.0.0",
37
+ "expo-location": ">=19.0.0",
38
+ "expo-task-manager": ">=14.0.0",
39
+ "react-native": "*"
40
+ },
41
+ "peerDependenciesMeta": {
42
+ "@react-native-async-storage/async-storage": {
43
+ "optional": true
44
+ }
45
+ }
46
+ }
package/src/http.js ADDED
@@ -0,0 +1,26 @@
1
+ import { Native } from './native'
2
+
3
+ /**
4
+ * POST a JSON body natively. Resolves to the HTTP status code, rejects on a
5
+ * network error. Resolves null when the native module isn't available.
6
+ */
7
+ export async function httpPost(url, headers = {}, body = {}, timeoutMs = 15000) {
8
+ if (!Native?.httpPost) return null
9
+ return Native.httpPost(url, headers || {}, typeof body === 'string' ? body : JSON.stringify(body), timeoutMs)
10
+ }
11
+
12
+ /**
13
+ * POST JSON, native first, fetch as fallback. Use this inside your
14
+ * TaskManager.defineTask location task. Resolves to the HTTP status.
15
+ */
16
+ export async function postJson(url, headers = {}, body = {}, timeoutMs = 15000) {
17
+ const payload = typeof body === 'string' ? body : JSON.stringify(body)
18
+ const nativeStatus = await httpPost(url, headers, payload, timeoutMs)
19
+ if (nativeStatus !== null) return nativeStatus
20
+ const res = await fetch(url, {
21
+ method: 'POST',
22
+ headers: { 'Content-Type': 'application/json', ...headers },
23
+ body: payload,
24
+ })
25
+ return res.status
26
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,74 @@
1
+ /** true on Android when the native module is linked. */
2
+ export const isAvailable: boolean
3
+
4
+ /** Lower-case Build.MANUFACTURER, e.g. "xiaomi", "tecno". Empty on iOS. */
5
+ export const manufacturer: string
6
+
7
+ export interface GuardOptions {
8
+ /** Title of the guard's notification (shown only after a background restore). */
9
+ notificationTitle?: string
10
+ /** Body of the guard's notification. */
11
+ notificationBody?: string
12
+ /** Android notification channel name shown in system settings. */
13
+ channelName?: string
14
+ }
15
+
16
+ /** Start (or keep) the guard. Call right after Location.startLocationUpdatesAsync. Cheap to repeat. */
17
+ export function startGuard(options?: GuardOptions): void
18
+ /** Stop the guard. Call together with Location.stopLocationUpdatesAsync. */
19
+ export function stopGuard(): void
20
+ /** Remove the guard's notification once tracking is started from the app screen again. */
21
+ export function demoteGuard(): void
22
+ /** expo-task-manager workaround. Call just before start/stopLocationUpdatesAsync. */
23
+ export function fixTaskService(): void
24
+
25
+ /** Native POST (Android). Resolves the HTTP status; null if the module is unavailable; rejects on network error. */
26
+ export function httpPost(url: string, headers?: Record<string, string>, body?: unknown, timeoutMs?: number): Promise<number | null>
27
+ /** Native POST first, fetch fallback. Resolves the HTTP status. */
28
+ export function postJson(url: string, headers?: Record<string, string>, body?: unknown, timeoutMs?: number): Promise<number>
29
+
30
+ /** true when the app is exempt from battery optimisation (always true on iOS). */
31
+ export function isBatteryUnrestricted(): boolean
32
+ /** Opens Android's "allow background" dialog. */
33
+ export function requestBatteryUnrestricted(): boolean
34
+ /** Opens the brand auto-start screen; false if no known screen (app-info opened instead). */
35
+ export function openAutoStartSettings(): boolean
36
+
37
+ export interface BrandStep {
38
+ brand: 'xiaomi' | 'oppo' | 'vivo' | 'tecno' | 'samsung'
39
+ text: string
40
+ }
41
+ /** Extra setting this phone's brand needs, or null. */
42
+ export function brandStep(appName?: string): BrandStep | null
43
+
44
+ export interface KeyValueStorage {
45
+ getItem(key: string): Promise<string | null>
46
+ setItem(key: string, value: string): Promise<void>
47
+ removeItem(key: string): Promise<void>
48
+ }
49
+
50
+ export interface OfflineQueueOptions {
51
+ storage: KeyValueStorage
52
+ /** Endpoint accepting POST { pings: [...] } */
53
+ batchUrl: string
54
+ getHeaders?: () => Record<string, string> | Promise<Record<string, string>>
55
+ key?: string
56
+ maxItems?: number
57
+ maxAgeMs?: number
58
+ chunkSize?: number
59
+ timeoutMs?: number
60
+ }
61
+
62
+ export interface OfflineQueue {
63
+ /** Save a ping before sending. Returns its id for ack(). */
64
+ enqueue(ping: Record<string, unknown>): Promise<string | null>
65
+ /** Server accepted the ping — remove it. */
66
+ ack(id: string | null): Promise<void>
67
+ /** Send all saved pings in chunks. Returns how many were delivered. */
68
+ flush(): Promise<number>
69
+ size(): Promise<number>
70
+ /** Best-effort flush, then delete everything (logout). */
71
+ clear(): Promise<void>
72
+ }
73
+
74
+ export function createOfflineQueue(options: OfflineQueueOptions): OfflineQueue
package/src/index.js ADDED
@@ -0,0 +1,66 @@
1
+ // Android-only. On iOS (or a build without the native module) every call is a
2
+ // safe no-op and httpPost resolves null so callers fall back to fetch.
3
+ import { Native } from './native'
4
+
5
+ export const isAvailable = !!Native
6
+ export const manufacturer = Native?.manufacturer || ''
7
+
8
+ /**
9
+ * Start (or keep) the guard. Call right after Location.startLocationUpdatesAsync,
10
+ * and it is cheap to call again on every location fix.
11
+ * The texts are used for the guard's own notification, shown only while the app
12
+ * was restored in the background with no screen.
13
+ */
14
+ export function startGuard({ notificationTitle, notificationBody, channelName } = {}) {
15
+ try { Native?.startGuard(notificationTitle ?? null, notificationBody ?? null, channelName ?? null) } catch {}
16
+ }
17
+
18
+ /** Stop the guard — call together with Location.stopLocationUpdatesAsync (e.g. logout). */
19
+ export function stopGuard() {
20
+ try { Native?.stopGuard() } catch {}
21
+ }
22
+
23
+ /** Remove the guard's notification once tracking was (re)started from the app screen. */
24
+ export function demoteGuard() {
25
+ try { Native?.demoteGuard() } catch {}
26
+ }
27
+
28
+ /** Call just before start/stopLocationUpdatesAsync (expo-task-manager workaround). */
29
+ export function fixTaskService() {
30
+ try { Native?.fixTaskService() } catch {}
31
+ }
32
+
33
+ /** true when Android won't put the app to sleep in the background (true on iOS). */
34
+ export function isBatteryUnrestricted() {
35
+ try { return Native ? Native.isIgnoringBatteryOptimizations() : true } catch { return true }
36
+ }
37
+
38
+ /** Opens Android's "allow background" dialog (or the battery list). */
39
+ export function requestBatteryUnrestricted() {
40
+ try { return !!Native?.requestIgnoreBatteryOptimizations() } catch { return false }
41
+ }
42
+
43
+ /** Opens the brand's auto-start screen; false (app-info opened instead) if unknown. */
44
+ export function openAutoStartSettings() {
45
+ try { return !!Native?.openAutoStartSettings() } catch { return false }
46
+ }
47
+
48
+ const BRAND_STEPS = [
49
+ { brand: 'xiaomi', match: ['xiaomi', 'redmi', 'poco'], text: app => `Turn ON "Autostart" for ${app}, then open Recent apps, long-press ${app} and tap the lock` },
50
+ { brand: 'oppo', match: ['oppo', 'realme', 'oneplus'], text: app => `Turn ON "Allow auto launch" (Auto startup) for ${app}` },
51
+ { brand: 'vivo', match: ['vivo', 'iqoo'], text: app => `Turn ON "Autostart" and "High background power usage" for ${app}` },
52
+ { brand: 'tecno', match: ['tecno', 'infinix', 'itel'], text: app => `Phone Master → turn ON "Auto-start" for ${app}` },
53
+ { brand: 'samsung', match: ['samsung'], text: app => `Background usage limits → "Never sleeping apps" → add ${app}` },
54
+ ]
55
+
56
+ /**
57
+ * The extra step this phone's brand needs (null when none).
58
+ * @param {string} appName shown in the instruction text
59
+ */
60
+ export function brandStep(appName = 'the app') {
61
+ const b = BRAND_STEPS.find(s => s.match.some(m => manufacturer.includes(m)))
62
+ return b ? { brand: b.brand, text: b.text(appName) } : null
63
+ }
64
+
65
+ export { httpPost, postJson } from './http'
66
+ export { createOfflineQueue } from './offlineQueue'
package/src/native.js ADDED
@@ -0,0 +1,4 @@
1
+ import { Platform } from 'react-native'
2
+ import { requireOptionalNativeModule } from 'expo-modules-core'
3
+
4
+ export const Native = Platform.OS === 'android' ? requireOptionalNativeModule('LocationKeepAlive') : null
@@ -0,0 +1,96 @@
1
+ import { postJson } from './http'
2
+
3
+ /**
4
+ * Write-ahead queue for location pings.
5
+ *
6
+ * Each ping is saved BEFORE it is sent and removed only after the server
7
+ * accepted it, so no ping is lost when the network is down, suspended by the
8
+ * OS, or the app is killed mid-request. Saved pings are sent later in chunks,
9
+ * with their original timestamps, so the server can rebuild the true route.
10
+ *
11
+ * @param {object} opts
12
+ * @param {object} opts.storage AsyncStorage-compatible { getItem, setItem, removeItem }
13
+ * @param {string} opts.batchUrl endpoint accepting POST { pings: [...] }
14
+ * @param {() => Promise<object>|object} [opts.getHeaders] e.g. Authorization
15
+ * @param {string} [opts.key] storage key
16
+ * @param {number} [opts.maxItems] oldest dropped beyond this (default 1500 ≈ 2 h at 5 s)
17
+ * @param {number} [opts.maxAgeMs] pings older than this are dropped (default 24 h)
18
+ * @param {number} [opts.chunkSize] pings per batch request (default 200)
19
+ * @param {number} [opts.timeoutMs] per request (default 20000)
20
+ */
21
+ export function createOfflineQueue({
22
+ storage,
23
+ batchUrl,
24
+ getHeaders = () => ({}),
25
+ key = 'location_keepalive_queue',
26
+ maxItems = 1500,
27
+ maxAgeMs = 24 * 60 * 60 * 1000,
28
+ chunkSize = 200,
29
+ timeoutMs = 20000,
30
+ }) {
31
+ let seq = 0
32
+
33
+ const read = async () => {
34
+ const raw = await storage.getItem(key)
35
+ return raw ? JSON.parse(raw) : []
36
+ }
37
+ // An empty queue is removed outright — nothing is left on the phone once
38
+ // every ping has been delivered.
39
+ const write = async (q) => {
40
+ if (q.length) await storage.setItem(key, JSON.stringify(q))
41
+ else await storage.removeItem(key)
42
+ }
43
+
44
+ return {
45
+ /** Save a ping before sending it. Returns its id (pass to ack). */
46
+ async enqueue(ping) {
47
+ try {
48
+ const id = `${Date.now()}-${seq++}`
49
+ const cutoff = Date.now() - maxAgeMs
50
+ let q = (await read()).filter(p => !p.ts || new Date(p.ts).getTime() >= cutoff)
51
+ q.push({ ...ping, __id: id })
52
+ if (q.length > maxItems) q = q.slice(q.length - maxItems)
53
+ await write(q)
54
+ return id
55
+ } catch {
56
+ return null
57
+ }
58
+ },
59
+
60
+ /** The server accepted this ping — drop it. */
61
+ async ack(id) {
62
+ if (!id) return
63
+ try { await write((await read()).filter(p => p.__id !== id)) } catch {}
64
+ },
65
+
66
+ /** Send everything saved, in chunks. Returns how many were delivered. */
67
+ async flush() {
68
+ let total = 0
69
+ try {
70
+ const headers = await getHeaders()
71
+ for (;;) {
72
+ const chunk = (await read()).slice(0, chunkSize)
73
+ if (!chunk.length) return total
74
+ const status = await postJson(batchUrl, headers, { pings: chunk.map(({ __id, ...p }) => p) }, timeoutMs)
75
+ // A rejected batch stays queued — dropping it would lose the pings
76
+ if (status < 200 || status >= 300) return total
77
+ const sent = new Set(chunk.map(p => p.__id))
78
+ await write((await read()).filter(p => !sent.has(p.__id)))
79
+ total += chunk.length
80
+ }
81
+ } catch {
82
+ return total
83
+ }
84
+ },
85
+
86
+ async size() {
87
+ try { return (await read()).length } catch { return 0 }
88
+ },
89
+
90
+ /** Logout: best-effort send, then delete everything. */
91
+ async clear() {
92
+ await this.flush().catch(() => {})
93
+ await storage.removeItem(key).catch(() => {})
94
+ },
95
+ }
96
+ }