fix: resolve Handler leak, race condition, and duplicate location send in speed calculation

This commit is contained in:
fiatcode 2026-05-02 16:25:47 +07:00
parent c9e49c6cbd
commit b5fabd980f
No known key found for this signature in database

View file

@ -57,6 +57,7 @@ class LocationTrackingService : Service() {
private var isTracking = false
private var isNetworkAvailable = true
private var bypassFilterOnce = false
private val speedHandler = Handler(Looper.getMainLooper())
private var currentConfig: TrackingConfig? = null
private var pendingSpeedLocation: Location? = null
@ -188,6 +189,7 @@ class LocationTrackingService : Service() {
Log.d(TAG, "stopTracking: set tracking_active=false")
fusedLocationProvider.stopLocationUpdates()
heartbeatScheduler.cancelHeartbeat()
speedHandler.removeCallbacksAndMessages(null)
releaseWakeLock()
stopForeground(STOP_FOREGROUND_REMOVE)
@ -236,9 +238,12 @@ class LocationTrackingService : Service() {
val nativeSpeed = if (location.hasSpeed()) location.speed else null
if (nativeSpeed == null || nativeSpeed <= 0) {
if (!speedRequestPending) {
pendingSpeedLocation = location
requestLocationForSpeedCalculation()
}
return
}
val traccarLocation = TraccarLocation(
timestamp = location.time,
@ -296,7 +301,7 @@ class LocationTrackingService : Service() {
if (speedRequestPending) return
speedRequestPending = true
Handler(Looper.getMainLooper()).postDelayed({
speedHandler.postDelayed({
fusedLocationProvider.getLastLocation { location ->
location?.let {
val calculatedSpeed = distanceFilterProcessor.getCalculatedSpeed(it)