GPS-Tracking cant be stopped with LocationManagerAPI

49 Views Asked by At

I have written this composable function to track the users position.

@SuppressLint("MissingPermission")
@Composable
fun GpsTracking() {
    val ctx = LocalContext.current
    val locationManager: LocationManager = ctx.getSystemService(Context.LOCATION_SERVICE) as LocationManager

    var latitude by remember { mutableStateOf(0.0) }
    var longitude by remember { mutableStateOf(0.0) }

    var tracking by remember { mutableStateOf(false) }

    var btnTextEnabled = if (tracking) "Ein" else "Aus"

    var locationListener: LocationListener? = null

    locationListener = object : LocationListener {
        override fun onLocationChanged(location: Location) {
            latitude = location.latitude
            longitude = location.longitude
            gpsList.add(System.currentTimeMillis().toString()+","+latitude+","+longitude+"\n")
        }
    }

    Button(onClick = { tracking = !tracking }) {
        Text(text = "GPS-Tracking: $btnTextEnabled")
    }

    DisposableEffect(tracking) {
        if (tracking) {
            Log.d("GPS-Tracking", "Tracking wird gestartet")
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 0f, locationListener as LocationListener
            )
            Log.d("GPS-Tracking", "Longitiude: $longitude\nLatitude: $latitude")
        } else {
            Log.d("GPS-Tracking", "Tracking wird gestoppt")
            locationManager.removeUpdates(locationListener as LocationListener)
            locationListener = null
        }

        onDispose {
            // Cleanup, if necessary
        }
    }
}

I try to controll the tracking with the boolean variable tracking. If its true the tracking should start and if it is false the tracking should stop.

But when i try to stop the tracking it is still tracking the position. Can you see the mistake in my code and give me some hints?

1

There are 1 best solutions below

0
Giedrius Kairys On

I believe you are creating a new LocationListener object on each composition. So you are trying to removeUpdates with a different object than it was started with. You need to remember your listener to reuse the same one.

Didn't test it but try something like this:

var locationListener = remember {
        object : LocationListener {
            override fun onLocationChanged(location: Location) {
                latitude = location.latitude
                longitude = location.longitude
                gpsList.add(System.currentTimeMillis().toString()+","+latitude+","+longitude+"\n")
            }
        }
    }