expo-location 58.0.13 → 58.0.14

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.
Files changed (66) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/android/build.gradle +2 -2
  3. package/android/src/main/AndroidManifest.xml +4 -0
  4. package/android/src/main/java/expo/modules/location/next/LocationModuleNext.kt +189 -10
  5. package/android/src/main/java/expo/modules/location/next/LocationPermissions.kt +65 -0
  6. package/android/src/main/java/expo/modules/location/next/LocationRecords.kt +91 -2
  7. package/android/src/main/java/expo/modules/location/next/LocationTaskConsumer.kt +205 -0
  8. package/android/src/main/java/expo/modules/location/next/WatchPosition.kt +8 -6
  9. package/android/src/main/java/expo/modules/location/next/locationForegroundService/BackgroundSessionOptions.kt +62 -0
  10. package/android/src/main/java/expo/modules/location/next/locationForegroundService/BackgroundSessionTypes.kt +32 -0
  11. package/android/src/main/java/expo/modules/location/next/locationForegroundService/ForegroundServiceExceptions.kt +53 -0
  12. package/android/src/main/java/expo/modules/location/next/locationForegroundService/LocationForegroundService.kt +142 -0
  13. package/android/src/main/java/expo/modules/location/next/locationForegroundService/ServiceNotification.kt +64 -0
  14. package/android/src/main/java/expo/modules/location/next/locationProviders/AndroidLocationProvider.kt +115 -7
  15. package/android/src/main/java/expo/modules/location/next/locationProviders/FallbackLocationProvider.kt +12 -3
  16. package/android/src/main/java/expo/modules/location/next/locationProviders/GmsLocationProvider.kt +79 -0
  17. package/android/src/main/java/expo/modules/location/next/locationProviders/LocationProvider.kt +48 -0
  18. package/ios/Providers/LocationsStreamer.swift +10 -4
  19. package/ios/next/LocationModuleNext.swift +4 -0
  20. package/ios/next/LocationNextExceptions.swift +0 -8
  21. package/ios/next/LocationUpdatesHandle/LocationUpdatesHandle.swift +6 -2
  22. package/ios/next/Position/LocationUpdateDiagnostics.swift +0 -3
  23. package/ios/next/Position/PositionUpdatesCompatibilitySource.swift +9 -1
  24. package/ios/next/Position/PositionUpdatesLiveSource.swift +5 -0
  25. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14-sources.jar +0 -0
  26. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14-sources.jar.md5 +1 -0
  27. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14-sources.jar.sha1 +1 -0
  28. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14-sources.jar.sha256 +1 -0
  29. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14-sources.jar.sha512 +1 -0
  30. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14.aar +0 -0
  31. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14.aar.md5 +1 -0
  32. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14.aar.sha1 +1 -0
  33. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14.aar.sha256 +1 -0
  34. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14.aar.sha512 +1 -0
  35. package/local-maven-repo/host/exp/exponent/expo.modules.location/{58.0.13/expo.modules.location-58.0.13.module → 58.0.14/expo.modules.location-58.0.14.module} +22 -22
  36. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14.module.md5 +1 -0
  37. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14.module.sha1 +1 -0
  38. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14.module.sha256 +1 -0
  39. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14.module.sha512 +1 -0
  40. package/local-maven-repo/host/exp/exponent/expo.modules.location/{58.0.13/expo.modules.location-58.0.13.pom → 58.0.14/expo.modules.location-58.0.14.pom} +1 -1
  41. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14.pom.md5 +1 -0
  42. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14.pom.sha1 +1 -0
  43. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14.pom.sha256 +1 -0
  44. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.14/expo.modules.location-58.0.14.pom.sha512 +1 -0
  45. package/package.json +2 -2
  46. package/plugin/build/withLocation.js +2 -0
  47. package/plugin/build/withLocation.js.map +1 -1
  48. package/plugin/src/withLocation.ts +2 -0
  49. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13-sources.jar +0 -0
  50. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13-sources.jar.md5 +0 -1
  51. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13-sources.jar.sha1 +0 -1
  52. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13-sources.jar.sha256 +0 -1
  53. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13-sources.jar.sha512 +0 -1
  54. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13.aar +0 -0
  55. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13.aar.md5 +0 -1
  56. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13.aar.sha1 +0 -1
  57. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13.aar.sha256 +0 -1
  58. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13.aar.sha512 +0 -1
  59. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13.module.md5 +0 -1
  60. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13.module.sha1 +0 -1
  61. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13.module.sha256 +0 -1
  62. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13.module.sha512 +0 -1
  63. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13.pom.md5 +0 -1
  64. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13.pom.sha1 +0 -1
  65. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13.pom.sha256 +0 -1
  66. package/local-maven-repo/host/exp/exponent/expo.modules.location/58.0.13/expo.modules.location-58.0.13.pom.sha512 +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 58.0.14
4
+
5
+ ### Patch Changes
6
+
7
+ - [Android] Add background location tracking. `LocationProvider` interface now has `getLocationTaskConsumerClass` and `getRegisteredTaskConsumerClass` methods, which return the `LocationTaskConsumer` class used to handle background location using TaskManager. Added `GmsLocationTaskConsumer` and `AndroidLocationTaskConsumer` implementations. Add `RECEIVE_BOOT_COMPLETED` to the manifest when the `isAndroidBackgroundLocationEnabled` is true. ([#50876](https://github.com/expo/expo/pull/50876) by [@HubertBer](https://github.com/HubertBer))
8
+ - [iOS] Keep `watchPositionAsync` alive while the app is in the background. ([#51327](https://github.com/expo/expo/pull/51327) by [@Wenszel](https://github.com/Wenszel))
9
+ - [next][iOS] Add `hasLocationServicesEnabled`. ([#51326](https://github.com/expo/expo/pull/51326) by [@Wenszel](https://github.com/Wenszel))
10
+ - [next][iOS] Report `ERR_LOCATION_SERVICES_DISABLED_GLOBALLY` from `expo-location/next` watchers when Location Services are turned off. ([#51325](https://github.com/expo/expo/pull/51325) by [@Wenszel](https://github.com/Wenszel))
11
+ - [next][iOS] Make `LocationUpdatesHandle.stop()` a no-op when the task is not registered. ([#51325](https://github.com/expo/expo/pull/51325) by [@Wenszel](https://github.com/Wenszel))
12
+ - [next][iOS] Keep `expo-location/next` watchers alive while the app is in the background. ([#51325](https://github.com/expo/expo/pull/51325) by [@Wenszel](https://github.com/Wenszel))
13
+ - [Android] Add a `LocationForegroundService` and helper methods to `start`/`update`/`stop` it. Update the position watchers so that they are running in background while the foreground service is running. ([#49995](https://github.com/expo/expo/pull/49995) by [@HubertBer](https://github.com/HubertBer))
14
+
3
15
  ## 58.0.13
4
16
 
5
17
  ### Patch Changes
@@ -4,13 +4,13 @@ plugins {
4
4
  }
5
5
 
6
6
  group = 'host.exp.exponent'
7
- version = '58.0.13'
7
+ version = '58.0.14'
8
8
 
9
9
  android {
10
10
  namespace "expo.modules.location"
11
11
  defaultConfig {
12
12
  versionCode 29
13
- versionName "58.0.13"
13
+ versionName "58.0.14"
14
14
  consumerProguardFiles("proguard-rules.pro")
15
15
  }
16
16
  }
@@ -7,5 +7,9 @@
7
7
  android:name=".services.LocationTaskService"
8
8
  android:exported="false"
9
9
  android:foregroundServiceType="location" />
10
+ <service
11
+ android:name=".next.locationForegroundService.LocationForegroundService"
12
+ android:exported="false"
13
+ android:foregroundServiceType="location" />
10
14
  </application>
11
15
  </manifest>
@@ -2,26 +2,52 @@ package expo.modules.location.next
2
2
 
3
3
  import android.content.Context
4
4
  import android.location.LocationManager
5
+ import android.os.Build
6
+ import android.util.Log
5
7
  import androidx.core.location.LocationManagerCompat
6
8
  import com.google.android.gms.common.ConnectionResult
7
9
  import com.google.android.gms.common.GoogleApiAvailability
8
10
  import com.google.android.gms.location.LocationServices
9
11
  import expo.modules.interfaces.permissions.Permissions
12
+ import expo.modules.interfaces.taskManager.TaskManagerInterface
13
+ import expo.modules.kotlin.exception.CodedException
10
14
  import expo.modules.kotlin.exception.Exceptions
11
15
  import expo.modules.kotlin.modules.Module
12
16
  import expo.modules.kotlin.modules.ModuleDefinition
13
17
  import expo.modules.kotlin.functions.Coroutine
14
18
  import expo.modules.kotlin.sharedobjects.SharedRef
19
+ import expo.modules.location.next.locationForegroundService.BackgroundSessionOptions
20
+ import expo.modules.location.next.locationForegroundService.BackgroundSessionState
21
+ import expo.modules.location.next.locationForegroundService.LocationForegroundService
22
+ import expo.modules.location.next.locationForegroundService.ServicePromotionFailedException
23
+ import expo.modules.location.next.locationForegroundService.ServicePromotionResult
24
+ import expo.modules.location.next.locationForegroundService.ServicePromotionTimedOutException
25
+ import expo.modules.location.next.locationForegroundService.SessionState
15
26
  import expo.modules.location.next.locationProviders.AndroidLocationProvider
16
27
  import expo.modules.location.next.locationProviders.EnableLocationServicesResult
17
28
  import expo.modules.location.next.locationProviders.FallbackLocationProvider
18
29
  import expo.modules.location.next.locationProviders.GmsLocationProvider
19
30
  import expo.modules.location.next.locationProviders.LocationProvider
31
+ import expo.modules.location.next.locationProviders.ProviderResult
32
+ import kotlinx.coroutines.CancellationException
20
33
  import kotlinx.coroutines.CompletableDeferred
21
34
  import expo.modules.location.next.locationProviders.WatchPositionParameters
22
35
  import expo.modules.location.next.locationProviders.PositionUpdatesSession
23
36
  import java.lang.ref.WeakReference
24
37
  import kotlin.time.Duration
38
+ import kotlin.time.Duration.Companion.seconds
39
+ import kotlinx.coroutines.withTimeoutOrNull
40
+ import java.util.concurrent.atomic.AtomicInteger
41
+ import kotlinx.coroutines.Job
42
+ import kotlinx.coroutines.delay
43
+ import kotlinx.coroutines.isActive
44
+ import kotlinx.coroutines.launch
45
+
46
+ private const val MISSING_NOTIFICATION_PERMISSION_WARNING =
47
+ "Starting the location foreground service without the `android.permission.POST_NOTIFICATIONS` " +
48
+ "permission. The service runs and location updates are not throttled, but its notification " +
49
+ "does not appear in the notification drawer."
50
+ class TaskManagerNotFoundException : CodedException("TaskManager module not found")
25
51
 
26
52
  class LocationModuleNext : Module() {
27
53
  private val context: Context
@@ -45,7 +71,10 @@ class LocationModuleNext : Module() {
45
71
  val androidLocationProviderInstance: SharedRef<LocationProvider> by lazy {
46
72
  SharedRef(AndroidLocationProvider(context))
47
73
  }
48
-
74
+ private val taskManager: TaskManagerInterface by lazy {
75
+ appContext.legacyModule<TaskManagerInterface>()
76
+ ?: throw TaskManagerNotFoundException()
77
+ }
49
78
  lateinit var currentLocationProvider: LocationProvider
50
79
 
51
80
  lateinit var locationManager: LocationManager
@@ -53,8 +82,22 @@ class LocationModuleNext : Module() {
53
82
  @Volatile
54
83
  private var locationServicesPrompt: CompletableDeferred<Boolean>? = null
55
84
 
85
+ @Volatile
86
+ var isForegrounded = false
87
+
88
+ private fun shouldWatchersRun() = isForegrounded || LocationForegroundService.isBackgroundLocationUnthrottled()
89
+
90
+ private fun updateWatchSessions() = synchronized(watchSessions) {
91
+ watchSessions.removeIf { it.get() == null }
92
+ val areUpdatesAllowed = shouldWatchersRun()
93
+ for (session in watchSessions) {
94
+ session.get()?.setUpdatesAllowed(areUpdatesAllowed)
95
+ }
96
+ }
97
+
56
98
  fun createPositionWatchHandle(initialParameters: WatchPositionParameters, session: PositionUpdatesSession): PositionWatchHandle = synchronized(watchSessions) {
57
- val pausableSession = PausableWatchSession(initialParameters, session)
99
+ val areUpdatesAllowed = shouldWatchersRun()
100
+ val pausableSession = PausableWatchSession(initialParameters, session, areUpdatesAllowed)
58
101
  watchSessions.add(WeakReference(pausableSession))
59
102
  return@synchronized PositionWatchHandle(pausableSession)
60
103
  }
@@ -67,6 +110,7 @@ class LocationModuleNext : Module() {
67
110
  listOf(fusedLocationProviderInstance.ref, androidLocationProviderInstance.ref)
68
111
  )
69
112
  locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
113
+ modulesStarted.incrementAndGet()
70
114
  }
71
115
 
72
116
  // Permissions
@@ -88,6 +132,15 @@ class LocationModuleNext : Module() {
88
132
  return@Coroutine permissionsManager.getLocationPermissions(background = true)
89
133
  }
90
134
 
135
+ AsyncFunction("requestNotificationPermissions") Coroutine { ->
136
+ permissionsManager.requestNotificationPermissions()
137
+ return@Coroutine permissionsManager.getNotificationPermissions(context)
138
+ }
139
+
140
+ AsyncFunction("getNotificationPermissions") Coroutine { ->
141
+ return@Coroutine permissionsManager.getNotificationPermissions(context)
142
+ }
143
+
91
144
  // Location providers
92
145
  Function("setLocationProvider") { locationProvider: SharedRef<LocationProvider> ->
93
146
  currentLocationProvider = locationProvider.ref
@@ -125,6 +178,43 @@ class LocationModuleNext : Module() {
125
178
  hasLocationServicesEnabled()
126
179
  }
127
180
 
181
+ Class(LocationUpdatesHandle::class) {
182
+ Constructor { taskName: String, profile: LocationProfile? ->
183
+ LocationUpdatesHandle(taskName, profile ?: LocationProfile.DEFAULT, currentLocationProvider)
184
+ }
185
+
186
+ Function("withProfile") { handle: LocationUpdatesHandle, profile: LocationProfile ->
187
+ handle.profile = profile
188
+ }
189
+
190
+ AsyncFunction("start") { handle: LocationUpdatesHandle ->
191
+ permissionsManager.ensureBackgroundPermissions()
192
+
193
+ val locationTaskConsumer = getExistingOrNewLocationTaskConsumer(handle, taskManager)
194
+ .getOrThrow("getLocationTaskConsumerClass")
195
+
196
+ val optionsMap = handle.profile.toBackgroundUpdatesParameters().toMap()
197
+ taskManager.registerTask(handle.taskName, locationTaskConsumer, optionsMap)
198
+ }
199
+
200
+ AsyncFunction("stop") { handle: LocationUpdatesHandle ->
201
+ val registeredConsumer = handle.locationProvider.getRegisteredTaskConsumerClass(taskManager, handle.taskName)
202
+ if (registeredConsumer is ProviderResult.Available) {
203
+ taskManager.unregisterTask(handle.taskName, registeredConsumer.value)
204
+ }
205
+ }
206
+
207
+ AsyncFunction("hasStarted") { handle: LocationUpdatesHandle ->
208
+ val registeredConsumer = handle.locationProvider.getRegisteredTaskConsumerClass(taskManager, handle.taskName)
209
+ return@AsyncFunction registeredConsumer is ProviderResult.Available
210
+ }
211
+
212
+ Function("status") { handle: LocationUpdatesHandle ->
213
+ val registeredConsumer = handle.locationProvider.getRegisteredTaskConsumerClass(taskManager, handle.taskName)
214
+ return@Function LocationTaskConsumer.statusOf(handle.taskName, registeredConsumer is ProviderResult.Available)
215
+ }
216
+ }
217
+
128
218
  AsyncFunction("enableLocationServices") Coroutine { ->
129
219
  if (hasLocationServicesEnabled()) {
130
220
  return@Coroutine true
@@ -161,6 +251,51 @@ class LocationModuleNext : Module() {
161
251
  }
162
252
  }
163
253
 
254
+ Class("BackgroundSession") {
255
+ StaticAsyncFunction("ensureStarted") Coroutine { backgroundSessionOptions: BackgroundSessionOptions? ->
256
+ if (!LocationForegroundService.isForegroundServiceRequired) {
257
+ return@Coroutine
258
+ }
259
+ permissionsManager.ensureForegroundServicePermissions()
260
+ if (!permissionsManager.hasNotificationPermission()) {
261
+ Log.w("ExpoLocation", MISSING_NOTIFICATION_PERMISSION_WARNING)
262
+ }
263
+
264
+ val requested = backgroundSessionOptions
265
+ val options = if (requested != null) {
266
+ BackgroundSessionOptions.persist(context, requested)
267
+ requested
268
+ } else {
269
+ BackgroundSessionOptions.readPersisted(context)
270
+ ?: BackgroundSessionOptions().also { BackgroundSessionOptions.persist(context, it) }
271
+ }
272
+
273
+ val sessionState = LocationForegroundService.startOrUpdate(context, options, updateOnly = !isForegrounded)
274
+ if (sessionState !is SessionState.Starting) {
275
+ return@Coroutine
276
+ }
277
+
278
+ when (val result = withTimeoutOrNull(4.seconds) { sessionState.promotion.await() }) {
279
+ is ServicePromotionResult.Failed ->
280
+ throw result.cause as? CodedException ?: ServicePromotionFailedException(result.cause)
281
+ ServicePromotionResult.Promoted -> {}
282
+ null -> throw ServicePromotionTimedOutException()
283
+ }
284
+ }
285
+
286
+ StaticAsyncFunction("stop") Coroutine { ->
287
+ val currentState = LocationForegroundService.state
288
+ if (currentState is SessionState.Starting) {
289
+ withTimeoutOrNull(4.seconds) { currentState.promotion.await() }
290
+ }
291
+ LocationForegroundService.stop(context)
292
+ }
293
+
294
+ StaticFunction("status") {
295
+ LocationForegroundService.status()
296
+ }
297
+ }
298
+
164
299
  Class(PositionWatchHandle::class) {
165
300
  Constructor {
166
301
  throw PositionWatchHandleCreationException()
@@ -194,11 +329,13 @@ class LocationModuleNext : Module() {
194
329
  }
195
330
 
196
331
  Function("status") { locationWatchHandle: PositionWatchHandle ->
197
- locationWatchHandle.session.status()
332
+ locationWatchHandle.session.status(isForegrounded)
198
333
  }
199
334
  }
200
335
 
201
336
  OnDestroy {
337
+ modulesStarted.decrementAndGet()
338
+ pollForegroundServiceJob?.cancel()
202
339
  synchronized(watchSessions) {
203
340
  for (session in watchSessions) {
204
341
  session.get()?.release()
@@ -207,19 +344,57 @@ class LocationModuleNext : Module() {
207
344
  }
208
345
 
209
346
  OnActivityEntersForeground {
210
- synchronized(watchSessions) {
211
- for (session in watchSessions) {
212
- session.get()?.onLifecycleChange(true)
347
+ isForegrounded = true
348
+ updateWatchSessions()
349
+
350
+ appContext.backgroundCoroutineScope.launch {
351
+ try {
352
+ BackgroundSessionOptions.readPersisted(context)?.let {
353
+ permissionsManager.ensureForegroundServicePermissions()
354
+ val sessionState = LocationForegroundService.startOrUpdate(context, it, updateOnly = !isForegrounded)
355
+ if (sessionState is SessionState.Starting) {
356
+ sessionState.promotion.await()
357
+ updateWatchSessions()
358
+ }
359
+ }
360
+ } catch (e: CancellationException) {
361
+ throw e
362
+ } catch (e: Exception) {
363
+ Log.w("ExpoLocation", "Could not restart the background session after entering the foreground", e)
213
364
  }
214
365
  }
215
366
  }
216
367
 
217
368
  OnActivityEntersBackground {
218
- synchronized(watchSessions) {
219
- watchSessions.removeIf { it.get() == null }
220
- for (session in watchSessions) {
221
- session.get()?.onLifecycleChange(false)
369
+ isForegrounded = false
370
+ updateWatchSessions()
371
+ startPollingForegroundService()
372
+ }
373
+ }
374
+
375
+ private var pollForegroundServiceJob: Job? = null
376
+
377
+ // Poll the foreground service so that if it promotes or dies we can update the watch sessions.
378
+ private fun startPollingForegroundService() {
379
+ if (pollForegroundServiceJob != null || Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
380
+ return
381
+ }
382
+ pollForegroundServiceJob = appContext.mainQueue.launch {
383
+ var previousAreUpdatesAllowed: Boolean? = null
384
+ while (isActive) {
385
+ val areUpdatesAllowed = shouldWatchersRun()
386
+
387
+ if (areUpdatesAllowed != previousAreUpdatesAllowed) {
388
+ updateWatchSessions()
389
+ }
390
+
391
+ if (LocationForegroundService.status().state == BackgroundSessionState.NOT_RUNNING || isForegrounded) {
392
+ pollForegroundServiceJob = null
393
+ return@launch
222
394
  }
395
+
396
+ previousAreUpdatesAllowed = areUpdatesAllowed
397
+ delay(1.seconds)
223
398
  }
224
399
  }
225
400
  }
@@ -227,4 +402,8 @@ class LocationModuleNext : Module() {
227
402
  private fun hasLocationServicesEnabled(): Boolean {
228
403
  return LocationManagerCompat.isLocationEnabled(locationManager)
229
404
  }
405
+
406
+ companion object {
407
+ @Volatile var modulesStarted = AtomicInteger(0)
408
+ }
230
409
  }
@@ -1,8 +1,10 @@
1
1
  package expo.modules.location.next
2
2
 
3
3
  import android.Manifest
4
+ import android.content.Context
4
5
  import android.os.Build
5
6
  import androidx.annotation.ChecksSdkIntAtLeast
7
+ import androidx.core.app.NotificationManagerCompat
6
8
  import expo.modules.kotlin.exception.CodedException
7
9
  import expo.modules.interfaces.permissions.Permissions
8
10
  import expo.modules.interfaces.permissions.PermissionsResponse
@@ -59,6 +61,52 @@ internal suspend fun Permissions.requestBackgroundPermissions() {
59
61
  requestPermissions(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
60
62
  }
61
63
 
64
+ @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.TIRAMISU)
65
+ private fun supportsNotificationPermission(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU
66
+
67
+ @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.P)
68
+ private fun supportsForegroundServicePermission(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P
69
+
70
+ @ChecksSdkIntAtLeast(api = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
71
+ private fun supportsForegroundServiceTypePermission(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE
72
+
73
+ internal suspend fun Permissions.requestNotificationPermissions() {
74
+ if (!supportsNotificationPermission()) {
75
+ return
76
+ }
77
+
78
+ if (!isPermissionPresentInManifest(Manifest.permission.POST_NOTIFICATIONS)) {
79
+ throw NoPermissionInManifestException("POST_NOTIFICATIONS")
80
+ }
81
+
82
+ requestPermissions(Manifest.permission.POST_NOTIFICATIONS)
83
+ }
84
+
85
+ internal suspend fun Permissions.getNotificationPermissions(context: Context): NotificationPermissionResponse {
86
+ if (!supportsNotificationPermission()) {
87
+ val areNotificationsEnabled = NotificationManagerCompat.from(context).areNotificationsEnabled()
88
+ val status = if (areNotificationsEnabled) {
89
+ LocationPermissionStatus.GRANTED
90
+ } else {
91
+ LocationPermissionStatus.DENIED
92
+ }
93
+ return NotificationPermissionResponse(
94
+ status = status,
95
+ granted = areNotificationsEnabled,
96
+ canAskAgain = areNotificationsEnabled
97
+ )
98
+ }
99
+
100
+ val permission = queryPermissions(Manifest.permission.POST_NOTIFICATIONS)
101
+ .responseFor(Manifest.permission.POST_NOTIFICATIONS)
102
+
103
+ return NotificationPermissionResponse(
104
+ status = LocationPermissionStatus.fromString(permission.status.status),
105
+ granted = permission.status == PermissionsStatus.GRANTED,
106
+ canAskAgain = permission.canAskAgain
107
+ )
108
+ }
109
+
62
110
  internal suspend fun Permissions.requestForegroundPermissions(options: RequestPermissionsOptions?) {
63
111
  val permissions = when (options?.accuracy ?: LocationAccuracyOption.FULL) {
64
112
  LocationAccuracyOption.FULL -> FOREGROUND_PERMISSIONS
@@ -111,8 +159,25 @@ internal fun Permissions.ensureForegroundPermissions() {
111
159
  }
112
160
  }
113
161
 
162
+ internal fun Permissions.ensureForegroundServicePermissions() {
163
+ ensureForegroundPermissions()
164
+
165
+ if (supportsForegroundServicePermission() && !isPermissionPresentInManifest(Manifest.permission.FOREGROUND_SERVICE)) {
166
+ throw NoPermissionInManifestException("FOREGROUND_SERVICE")
167
+ }
168
+ if (supportsForegroundServiceTypePermission() && !isPermissionPresentInManifest(Manifest.permission.FOREGROUND_SERVICE_LOCATION)) {
169
+ throw NoPermissionInManifestException("FOREGROUND_SERVICE_LOCATION")
170
+ }
171
+ }
172
+
173
+ internal fun Permissions.hasNotificationPermission(): Boolean =
174
+ !supportsNotificationPermission() || hasGrantedPermissions(Manifest.permission.POST_NOTIFICATIONS)
175
+
114
176
  internal fun Permissions.ensureBackgroundPermissions() {
115
177
  ensureForegroundPermissions()
178
+ if (!isPermissionPresentInManifest(Manifest.permission.RECEIVE_BOOT_COMPLETED)) {
179
+ throw NoPermissionInManifestException("RECEIVE_BOOT_COMPLETED")
180
+ }
116
181
  if (!supportsBackgroundPermission()) {
117
182
  return
118
183
  }
@@ -2,15 +2,21 @@ package expo.modules.location.next
2
2
 
3
3
  import android.location.Location
4
4
  import android.os.Build
5
+ import android.os.BaseBundle
6
+ import android.os.Bundle
7
+ import android.os.PersistableBundle
5
8
  import expo.modules.kotlin.records.Field
6
9
  import expo.modules.kotlin.records.Record
7
10
  import expo.modules.kotlin.types.Enumerable
8
11
  import expo.modules.kotlin.types.OptimizedRecord
12
+ import expo.modules.location.next.locationProviders.BackgroundUpdatesParameters
9
13
  import expo.modules.location.next.locationProviders.GetCurrentPositionOptions
10
14
  import expo.modules.location.next.locationProviders.LocationPriority
11
15
  import expo.modules.location.next.locationProviders.WatchPositionParameters
12
16
  import kotlin.time.Duration
13
17
  import kotlin.time.Duration.Companion.seconds
18
+ import kotlin.time.Duration.Companion.hours
19
+ import kotlin.time.Duration.Companion.minutes
14
20
 
15
21
  enum class LocationPermissionStatus(val value: String) : Enumerable {
16
22
  GRANTED("granted"),
@@ -43,10 +49,20 @@ enum class LocationAccuracyOption(val value: String) : Enumerable {
43
49
  REDUCED("reduced")
44
50
  }
45
51
 
52
+ @OptimizedRecord
46
53
  class RequestPermissionsOptions(
47
54
  @Field val accuracy: LocationAccuracyOption? = null
48
55
  ) : Record
49
56
 
57
+ @OptimizedRecord
58
+ class NotificationPermissionResponse(
59
+ @Field val status: LocationPermissionStatus,
60
+ @Field val granted: Boolean,
61
+ @Field val canAskAgain: Boolean,
62
+ @Field val expires: String = "never"
63
+ ) : Record
64
+
65
+ @OptimizedRecord
50
66
  class LocationPermissionResponse(
51
67
  @Field val status: LocationPermissionStatus,
52
68
  @Field val granted: Boolean,
@@ -85,6 +101,15 @@ enum class LocationProfile(val value: String) : Enumerable {
85
101
  LOW_POWER -> WatchPositionParameters(LocationPriority.LOW_POWER, 60.seconds, 300.seconds)
86
102
  }
87
103
  }
104
+
105
+ fun toBackgroundUpdatesParameters() = when (this) {
106
+ DEFAULT -> BackgroundUpdatesParameters(LocationPriority.BALANCED_POWER_ACCURACY, 1.minutes, 5.minutes, 100f)
107
+ AUTOMOTIVE_NAVIGATION -> BackgroundUpdatesParameters(LocationPriority.HIGH_ACCURACY, 1.seconds, Duration.ZERO, 0f)
108
+ OTHER_NAVIGATION -> BackgroundUpdatesParameters(LocationPriority.HIGH_ACCURACY, 5.seconds, 30.seconds, 10f)
109
+ FITNESS -> BackgroundUpdatesParameters(LocationPriority.HIGH_ACCURACY, 10.seconds, 2.minutes, 25f)
110
+ AIRBORNE -> BackgroundUpdatesParameters(LocationPriority.HIGH_ACCURACY, 1.seconds, Duration.ZERO, 0f)
111
+ LOW_POWER -> BackgroundUpdatesParameters(LocationPriority.LOW_POWER, 15.minutes, 1.hours, 500f)
112
+ }
88
113
  }
89
114
 
90
115
  class GetPositionOptions(
@@ -103,7 +128,21 @@ class GetPositionOptions(
103
128
  class Coordinates(
104
129
  @Field val latitude: Double,
105
130
  @Field val longitude: Double
106
- ) : Record
131
+ ) : Record {
132
+ private fun BaseBundle.putCoordinateFields() {
133
+ putDouble("latitude", latitude)
134
+ putDouble("longitude", longitude)
135
+ }
136
+
137
+ fun toPersistableBundle() = PersistableBundle().apply { putCoordinateFields() }
138
+
139
+ fun toBundle() = Bundle().apply { putCoordinateFields() }
140
+ }
141
+
142
+ fun PersistableBundle.toCoordinates(): Coordinates = Coordinates(
143
+ getDouble("latitude"),
144
+ getDouble("longitude")
145
+ )
107
146
 
108
147
  @OptimizedRecord
109
148
  class Position(
@@ -120,7 +159,57 @@ class Position(
120
159
  @Field val verticalAccuracy: Double? = null,
121
160
  @Field val speedAccuracy: Double? = null,
122
161
  @Field val headingAccuracy: Double? = null
123
- ) : Record
162
+ ) : Record {
163
+ private fun BaseBundle.putPositionFields() {
164
+ putDouble("timestamp", timestamp)
165
+ putBoolean("mocked", mocked)
166
+ mslAltitude?.let { putDouble("mslAltitude", it) }
167
+ altitude?.let { putDouble("altitude", it) }
168
+ speed?.let { putDouble("speed", it) }
169
+ heading?.let { putDouble("heading", it) }
170
+ horizontalAccuracy?.let { putDouble("horizontalAccuracy", it) }
171
+ verticalAccuracy?.let { putDouble("verticalAccuracy", it) }
172
+ speedAccuracy?.let { putDouble("speedAccuracy", it) }
173
+ headingAccuracy?.let { putDouble("headingAccuracy", it) }
174
+ }
175
+
176
+ fun toPersistableBundle() = PersistableBundle().apply {
177
+ putPersistableBundle("coordinates", coordinates.toPersistableBundle())
178
+ putPositionFields()
179
+ }
180
+
181
+ fun toBundle() = Bundle().apply {
182
+ putBundle("coordinates", coordinates.toBundle())
183
+ putPositionFields()
184
+ }
185
+ }
186
+
187
+ private fun PersistableBundle.getDoubleOrNull(key: String): Double? =
188
+ if (containsKey(key)) {
189
+ getDouble(key)
190
+ } else {
191
+ null
192
+ }
193
+
194
+ fun PersistableBundle.toPosition(): Position? {
195
+ val coordinates = getPersistableBundle("coordinates")?.toCoordinates() ?: return null
196
+ if (!containsKey("timestamp")) {
197
+ return null
198
+ }
199
+ return Position(
200
+ coordinates = coordinates,
201
+ timestamp = getDouble("timestamp"),
202
+ mocked = getBoolean("mocked"),
203
+ mslAltitude = getDoubleOrNull("mslAltitude"),
204
+ altitude = getDoubleOrNull("altitude"),
205
+ speed = getDoubleOrNull("speed"),
206
+ heading = getDoubleOrNull("heading"),
207
+ horizontalAccuracy = getDoubleOrNull("horizontalAccuracy"),
208
+ verticalAccuracy = getDoubleOrNull("verticalAccuracy"),
209
+ speedAccuracy = getDoubleOrNull("speedAccuracy"),
210
+ headingAccuracy = getDoubleOrNull("headingAccuracy")
211
+ )
212
+ }
124
213
 
125
214
  fun Location.mslAltitude(): Double? {
126
215
  return if (Build.VERSION.SDK_INT >= 34 && hasMslAltitude()) {