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