无法使用 LocationManagerAPI 停止 GPS 跟踪

问题描述 投票:0回答:1

我编写了这个可组合函数来跟踪用户位置。

@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
        }
    }
}

我尝试使用布尔变量跟踪来控制跟踪。如果为真,则应开始跟踪;如果为假,则应停止跟踪。

但是当我尝试停止跟踪时,它仍在跟踪位置。你能看到我代码中的错误并给我一些提示吗?

android kotlin android-jetpack-compose android-gps
1个回答
0
投票

我相信您正在每个组合上创建一个新的 LocationListener 对象。因此,您尝试使用与开始时不同的对象来删除更新。您需要记住您的听众才能重复使用同一个听众。

没有测试它,但尝试这样的事情:

var locationListener = remember {
        object : LocationListener {
            override fun onLocationChanged(location: Location) {
                latitude = location.latitude
                longitude = location.longitude
                gpsList.add(System.currentTimeMillis().toString()+","+latitude+","+longitude+"\n")
            }
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.