我写了这个可组合的函数来跟踪用户的位置。
@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
}
}
}
我试着用布尔变量tracking来控制跟踪。如果为真,则应开始跟踪,如果为假,则应停止跟踪。
但是当我试图停止跟踪时,它仍然在跟踪位置。你能看出我代码中的错误并给我给予吗?
1条答案
按热度按时间g52tjvyc1#
我相信您正在为每个组合创建一个新的LocationObject对象。因此,您正在尝试使用与启动时不同的对象删除更新。您需要记住您的侦听器以重用同一个侦听器。
我没有试过,但试过这样的东西: