capacitor-background-geolocation: [Bug]: Android version stops sending updates
Required Reading
- Confirmed
Plugin Version
6.1.5
Cap Doctor
π Capacitor Doctor π
Latest Dependencies:
@capacitor/cli: 7.2.0
@capacitor/core: 7.2.0
@capacitor/android: 7.2.0
@capacitor/ios: 7.2.0
Installed Dependencies:
@capacitor/ios: not installed
@capacitor/cli: 6.2.1
@capacitor/core: 6.2.1
@capacitor/android: 6.2.1
[success] Android looking great! π
Mobile operating-system(s)
- iOS
- Android
Device Manufacturer(s) and Model(s)
Galaxy Tab Active4 Pro 5G
Device operating-systems(s)
Android 14
What happened?
We use the plugin for 24/7 tracking of vehicles (fire department). For this, the tracking is non-stop active, and sending the results to our server.
We are investigating the issue where the app randomly (in the sense that we still are uncertain about the conditions) stops sending updates. When resetting the tracking (on/off) through the UI, the app resumes sending. At that point, we receive a huge burst of positions, which indicates that the tracking part remains operational, and that the issue resides in the sending module stopping working.
In order to futher investigate the issue, we added Sentry monitoring. Sentry has reported ApplicationNotResponding (ANR) errors on the background part, although at this point to us it is unclear whether this is related to the above issue. Below is the relevant stacktrace.
There is nothing registered in the breadcrumbs beforehand, so no indication what can have triggered this.
Plugin Code and/or Config
import * as Sentry from '@sentry/react'
import BackgroundGeolocation from '@transistorsoft/capacitor-background-geolocation'
import { SecureStoragePlugin } from 'capacitor-secure-storage-plugin'
import { useCallback, useEffect, useState } from 'react'
let heartbeatSubscription = null
const registerHeartbeatHandler = () => {
if (heartbeatSubscription) {
heartbeatSubscription.remove()
heartbeatSubscription = null
}
heartbeatSubscription = BackgroundGeolocation.onHeartbeat(async () => {
try {
Sentry.addBreadcrumb({
category: 'Tracking',
message: 'Heartbeat triggered',
level: 'info',
})
await BackgroundGeolocation.getCurrentPosition()
Sentry.addBreadcrumb({
category: 'Tracking',
message: 'Heartbeat position acquired successfully',
level: 'info',
})
} catch (error) {
Sentry.captureException(error, {
tags: { operation: 'heartbeatHandler' },
})
}
})
}
export const loadPlugin = async () => {
await BackgroundGeolocation.ready({
allowIdenticalLocations: true,
backgroundPermissionRationale: {
message:
'Enable background tracking so that you can close the app and still send the vehicle possition. Also allow app to not be paused when unused.',
},
batchSync: false,
desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
distanceFilter: 0, //needs to be zero if we want timebased
locationTemplate: '{"lat":<%= latitude %>,"long":<%= longitude %>}',
locationUpdateInterval: 5000, //interval for updates, doesn't work accurately but is around the number set
logLevel: BackgroundGeolocation.LOG_LEVEL_ERROR,
notification: {
//Notification needs to be displayed to let the plugin work
title: 'Background tracking engaged',
text: 'INA Companion is tracking location',
},
reset: false,
startOnBoot: false,
stopOnTerminate: true,
stopTimeout: 5, //amount of minutes after which plugin considers statioanry and creates a geofence
heartbeatInterval: 1800, //interval for sending forced location to server (30 minutes)
}).then(async (state) => {
await BackgroundGeolocation.setConfig({
heartbeatInterval: 1800,
})
if (state.enabled) {
await BackgroundGeolocation.setConfig({
enableHeadless: true,
})
registerHeartbeatHandler()
}
})
}
export const startTracking = async (unitId) => {
Sentry.addBreadcrumb({
category: 'Tracking',
message: 'Starting location tracking',
level: 'info',
data: { vehicleId: unitId },
})
const usernameValue = await SecureStoragePlugin.get({ key: 'username' }).catch((error) => {
Sentry.captureException(error, {
tags: { operation: 'startTracking.getUsername' },
})
return { value: '' }
})
const passwordValue = await SecureStoragePlugin.get({ key: 'password' }).catch((error) => {
Sentry.captureException(error, {
tags: { operation: 'startTracking.getPassword' },
})
return { value: '' }
})
const urlValue = await SecureStoragePlugin.get({ key: 'url' }).catch((error) => {
Sentry.captureException(error, {
tags: { operation: 'startTracking.getUrl' },
})
return { value: '' }
})
const encodedCredentials = btoa(`${usernameValue.value}:${passwordValue.value}`)
await BackgroundGeolocation.setConfig({
stopOnTerminate: false,
startOnBoot: true,
enableHeadless: true,
url: `${urlValue.value}/companion/units/${unitId}/location`,
headers: {
Authorization: `Basic ${encodedCredentials}`,
},
})
registerHeartbeatHandler()
await BackgroundGeolocation.start()
Sentry.addBreadcrumb({
category: 'Tracking',
message: 'Location tracking started successfully',
level: 'info',
data: { vehicleId: unitId },
})
}
export const stopTracking = async (clearVehicleId = false) => {
Sentry.addBreadcrumb({
category: 'Tracking',
message: 'Stopping location tracking',
level: 'info',
data: { clearVehicleId },
})
const config = {
stopOnTerminate: true,
startOnBoot: false,
}
if (clearVehicleId) {
config.url = ''
}
await BackgroundGeolocation.setConfig(config)
if (heartbeatSubscription) {
heartbeatSubscription.remove()
heartbeatSubscription = null
}
await BackgroundGeolocation.stop()
Sentry.addBreadcrumb({
category: 'Tracking',
message: 'Location tracking stopped successfully',
level: 'info',
})
}
export const useIsTracking = () => {
const [tracking, setTracking] = useState(false)
const refreshTrackingState = useCallback(() => {
BackgroundGeolocation.getState().then((state) => setTracking(state.enabled))
}, [])
useEffect(() => {
const subscription = BackgroundGeolocation.onEnabledChange(setTracking)
return subscription.remove
}, [])
useEffect(() => {
refreshTrackingState()
}, [refreshTrackingState])
return [tracking, refreshTrackingState]
}
export const useVehicleId = () => {
const [vehicleId, setVehicleId] = useState('')
const refreshVehicleId = useCallback(() => {
getTrackingVehicleId().then(setVehicleId)
}, [])
useEffect(() => {
refreshVehicleId()
}, [refreshVehicleId])
return [vehicleId, refreshVehicleId]
}
const getTrackingVehicleId = async () => {
const state = await BackgroundGeolocation.getState()
if (!state.url) return ''
const match = state.url.match(/units\/([^/]+)\/location/)
return match[1]
}
Relevant log output
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Comments: 16 (5 by maintainers)
@tanuj-g you require assistance with using the library. What you describe is what we do, and we implemented this based on the documentation of the library. If you require custom assistance from @christocracy , I think it better to start a dedicated post on it instead of high-jacking the bug report of a very specific behavior of the app.
Yes
No
You are free to manually call .sync() at any time to initiate the plug-in http service. You can also call .getCount() to determine if there are currently records in the database.
I suggest you implement BackgroundFetch, already included as a dependency, for periodic callbacks.