Skip to content

[Bug]: Location not fetching when app is on foreground and moving state is true #2522

@sametfiyuu

Description

@sametfiyuu

Required Reading

  • Confirmed

Plugin Version

4.19.0

Mobile operating-system(s)

  • iOS
  • Android

Device Manufacturer(s) and Model(s)

Samsun A72

Device operating-systems(s)

Android 14

React Native / Expo version

0.81.5

What happened?

Hello, i noticed that even though my app is in foreground, it's not collecting the location. I only can see location and http logs after moving app to foreground from background or change my location (even app is on background). I'm not changing my location but since stopTimeout is 5 minutes, my is_moving state is true.

I used this script to see logs: adb logcat "*:S" TSLocationManager:V ActivityManager:V

on the log, i foregrounded app and it collected location and posted http. after that i observed no log.

Thanks in advance.

Plugin Code and/or Config

//CONFIG FILE

await BackgroundGeolocation.ready({
          desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
          stopTimeout: 5,
          heartbeatInterval: 60,
          stopOnStationary: false,
          stopOnTerminate: false,
          disableStopDetection: true,
          pausesLocationUpdatesAutomatically: false,
          stationaryRadius: 25,
          enableHeadless: true,
          logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
          showsBackgroundLocationIndicator: true,
          startOnBoot: true,
          preventSuspend: true,
          autoSync: true,
          isMoving: true,
          geofenceModeHighAccuracy: true,
          geofenceInitialTriggerEntry: true,
          debug: true,
          maxRecordsToPersist: 100,
          logMaxDays: 1,
          maxDaysToPersist: 1,
          locationAuthorizationRequest: 'Always' as LocationAuthorizationRequest,
          backgroundPermissionRationale: {
            title: permissionTitle,
            message: permissionMessage,
            positiveAction: permissionPositiveAction,
            negativeAction: permissionNegativeAction
          },
          url: `URL`,
          headers: {
            'api-key': Config.TRANSISTOR_API_KEY,
            authorization: `Bearer ${accessToken}`
          },
          params: {
            carrierId,
            msisdn: carrierMsidn,
            version: appVersion,
            deviceId
          }
        }).then(async () => {
          try {
            const location = await getCurrentLocation()
            await BackgroundGeolocation.insertLocation({
              ...location,
              extras: { ...location.extras, action: LocationEventName.SystemConfig }
            })
          } catch (error) {
            // Ignore errors for SystemConfig location tracking
            console.warn('Failed to send SystemConfig location', error)
          }

          try {
            setHasPermissionBeenRequested(true)
            const status = await BackgroundGeolocation.requestPermission()
            hasPermissionBeenChecked.current = true

            const isDenied = status === BackgroundGeolocation.AUTHORIZATION_STATUS_DENIED
            const isWhenInUse = status === BackgroundGeolocation.AUTHORIZATION_STATUS_WHEN_IN_USE

            if (isDenied || isWhenInUse) {
              isInitializing.current = false
              setShouldShowLocationModal(true)
              return
            }
          } catch (permissionError) {
            setHasPermissionBeenRequested(true)
            hasPermissionBeenChecked.current = true
            const errorMessage = permissionError instanceof Error ? permissionError.message : String(permissionError)
            console.warn('Location permission request failed:', errorMessage)
            isInitializing.current = false
            setShouldShowLocationModal(true)
            return
          }

          setIsEnabled(true)
          checkActiveGeofencesOnForeground()
        })
      } catch (error) {
        console.warn('Failed to initialize BackgroundGeolocation:', error)
        isInitializing.current = false
      } finally {
        isInitializing.current = false
      }
    },

// LISTENERS
  const onLocation = BackgroundGeolocation.onLocation(async location => {
      dispatch(setLocation(location.coords))
    })

  const onHttp = BackgroundGeolocation.onHttp(event => {
      if (event.status !== 401 || isUnauthorizedLogoutRef.current) {
        return
      }
    })

// HEADLESS
const HeadlessGeofenceTask = async event => {
  const { name, params } = event

  if (name === 'geofence') {
    const { identifier, action, extras } = params
    const geofenceType = extras?.geofenceType

    if (action === 'ENTER') {
      try {
        const storage = new MMKV()
        const storageKeyMap = {
          RESTAURANT: 'EnteredRestaurantGeofences',
          ORDER: 'EnteredOrderGeofences',
          CALL: 'EnteredCallGeofences'
        }
        const storageKey = storageKeyMap[geofenceType] || 'EnteredOrderGeofences'

        const currentValue = storage.getString(storageKey)
        const currentItems = currentValue ? JSON.parse(currentValue) : []

        if (!currentItems.includes(identifier)) {
          currentItems.push(identifier)
          storage.set(storageKey, JSON.stringify(currentItems))
        }
      } catch (error) {
        Sentry.captureException(error, {
          tags: { component: 'HeadlessTask', function: 'HeadlessGeofenceTask' },
          extra: { identifier, action, geofenceType }
        })
      }
    }
  }
}

BackgroundGeolocation.registerHeadlessTask(HeadlessGeofenceTask)

AppRegistry.registerComponent(appName, () => App)

Relevant log output

03-05 16:25:32.719  1608  4324 I ActivityManager: Killing 28482:com.samsung.android.forest/1000 (adj 999): empty #33
03-05 16:25:32.964  1608  1949 I ActivityManager: Changes in 10094 5 to 15, 56 to 0
03-05 16:26:15.697  1608  1899 I ActivityManager: Killing 7172:com.samsung.android.scs/u0a105 (adj 999): empty #33
03-05 16:26:16.465 28850 28850 D TSLocationManager: [c.t.l.l.LifecycleManager onStart] ☯️  onStart
03-05 16:26:16.492  1608  1899 I ActivityManager: Changes in 10319 4 to 2, 57 to 63
03-05 16:26:16.494 28850 28850 D TSLocationManager: [c.t.l.l.LifecycleManager onResume] ☯️  onResume
03-05 16:26:16.667 28850 28850 I TSLocationManager: [c.t.l.l.TSLocationManager a] 
03-05 16:26:16.667 28850 28850 I TSLocationManager: ╔═════════════════════════════════════════════
03-05 16:26:16.667 28850 28850 I TSLocationManager: ║ getCurrentPosition LocationResult: 40 (673ms old)
03-05 16:26:16.667 28850 28850 I TSLocationManager: ╠═════════════════════════════════════════════
03-05 16:26:16.667 28850 28850 I TSLocationManager: ╟─ 📍  Location[flp 41.093600,28.977472 hAcc=1.0 et=+5h5m32s295ms alt=65.0 bear=0.0 mock], time: 1772717175986
03-05 16:26:16.715  1608  2266 I ActivityManager: Changes in 10130 19 to 5, 0 to 56
03-05 16:26:16.723 28850 28850 I TSLocationManager: [c.t.l.l.TSLocationManager onSingleLocationResult] 
03-05 16:26:16.723 28850 28850 I TSLocationManager:   🔵  Acquired current position
03-05 16:26:16.723 28850 28850 D TSLocationManager: [c.t.l.l.TSLocationManager a] Median accuracy: 14.859
03-05 16:26:16.735 28850  2475 I TSLocationManager: [c.t.l.d.s.SQLiteLocationDAO persist] 
03-05 16:26:16.735 28850  2475 I TSLocationManager:   ✅  INSERT: ec8eeb45-1e3e-444b-9683-4820a6df946e
03-05 16:26:16.736 28850 28850 I TSLocationManager: [c.t.l.l.TSLocationManager a] 
03-05 16:26:16.736 28850 28850 I TSLocationManager: ╔═════════════════════════════════════════════
03-05 16:26:16.736 28850 28850 I TSLocationManager: ║ getCurrentPosition LocationResult: 41 (750ms old)
03-05 16:26:16.736 28850 28850 I TSLocationManager: ╠═════════════════════════════════════════════
03-05 16:26:16.736 28850 28850 I TSLocationManager: ╟─ 📍  Location[flp 41.093600,28.977472 hAcc=1.0 et=+5h5m32s295ms alt=65.0 bear=0.0 mock], time: 1772717175986
03-05 16:26:16.742 28850  2475 D TSLocationManager: [c.t.l.d.s.SQLiteLocationDAO shrink] 
03-05 16:26:16.742 28850  2475 D TSLocationManager:   ℹ️  SHRINK: 100
03-05 16:26:16.744 28850 28850 I TSLocationManager: [c.t.l.l.TSLocationManager onSingleLocationResult] 
03-05 16:26:16.744 28850 28850 I TSLocationManager:   🔵  Acquired current position
03-05 16:26:16.745 28850 28850 D TSLocationManager: [c.t.l.l.TSLocationManager a] Median accuracy: 14.859
03-05 16:26:16.761 28850  2479 I TSLocationManager: [c.t.l.d.s.SQLiteLocationDAO persist] 
03-05 16:26:16.761 28850  2479 I TSLocationManager:   ✅  INSERT: 5394ab16-8cdd-4894-ba14-dcacae12148a
03-05 16:26:16.768 28850  2479 D TSLocationManager: [c.t.l.d.s.SQLiteLocationDAO shrink] 
03-05 16:26:16.768 28850  2479 D TSLocationManager:   ℹ️  SHRINK: 100
03-05 16:26:16.770 28850  2475 I TSLocationManager: [c.t.l.http.HttpService flush] 
03-05 16:26:16.770 28850  2475 I TSLocationManager: ╔═════════════════════════════════════════════
03-05 16:26:16.770 28850  2475 I TSLocationManager: ║ HTTP Service (count: 2)
03-05 16:26:16.770 28850  2475 I TSLocationManager: ╠═════════════════════════════════════════════
03-05 16:26:16.771 28850  2479 I TSLocationManager: [c.t.l.http.HttpService flush] 
03-05 16:26:16.771 28850  2479 I TSLocationManager:   ℹ️  HttpService is busy
03-05 16:26:16.831  1608  1899 I ActivityManager: Changes in 10137 2 to 5, 63 to 56
03-05 16:26:16.877 28850 28850 I TSLocationManager: [c.t.l.u.BackgroundTaskManager$Task start] ⏳ startBackgroundTask: 25
03-05 16:26:16.881 28850  2475 D TSLocationManager: [c.t.l.d.s.SQLiteLocationDAO first] 
03-05 16:26:16.881 28850  2475 D TSLocationManager:   ✅  Locked 1 records
03-05 16:26:16.882 28850  2475 I TSLocationManager: [c.t.l.http.HttpService a] 
03-05 16:26:16.882 28850  2475 I TSLocationManager:   🔵  HTTP POST: ec8eeb45-1e3e-444b-9683-4820a6df946e
03-05 16:26:17.429 28850  2540 I TSLocationManager: [c.t.l.http.HttpService$f onResponse] 
03-05 16:26:17.429 28850  2540 I TSLocationManager:   🔵  Response: 200
03-05 16:26:17.431 28850  2540 D TSLocationManager: [c.t.l.d.s.SQLiteLocationDAO destroy] 
03-05 16:26:17.431 28850  2540 D TSLocationManager:   ✅  DESTROY: ec8eeb45-1e3e-444b-9683-4820a6df946e
03-05 16:26:17.442 28850  2540 D TSLocationManager: [c.t.l.d.s.SQLiteLocationDAO first] 
03-05 16:26:17.442 28850  2540 D TSLocationManager:   ✅  Locked 1 records
03-05 16:26:17.443 28850  2540 I TSLocationManager: [c.t.l.http.HttpService a] 
03-05 16:26:17.443 28850  2540 I TSLocationManager:   🔵  HTTP POST: 5394ab16-8cdd-4894-ba14-dcacae12148a
03-05 16:26:17.561 28850  2545 I TSLocationManager: [c.t.l.http.HttpService$f onResponse] 
03-05 16:26:17.561 28850  2545 I TSLocationManager:   🔵  Response: 200
03-05 16:26:17.563 28850  2545 D TSLocationManager: [c.t.l.d.s.SQLiteLocationDAO destroy] 
03-05 16:26:17.563 28850  2545 D TSLocationManager:   ✅  DESTROY: 5394ab16-8cdd-4894-ba14-dcacae12148a
03-05 16:26:17.570 28850  2545 I TSLocationManager: [c.t.l.u.BackgroundTaskManager$Task stop] ⏳ stopBackgroundTask: 25
03-05 16:26:22.725  1608  1949 I ActivityManager: Changes in 10130 5 to 15, 56 to 0

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions