【发布时间】:2023-01-31 20:43:51
【问题描述】:
如何在 Android 中创建在后台运行的位置跟踪服务,即使该应用程序已完全终止?只要设备的位置改变 100 米,服务就应该启动,如果设备静止,服务就应该停止。此外,我需要该服务尽可能省电。我曾尝试将前台服务与 Activity Recognition API 组合使用,但当应用程序被完全杀死时它似乎不起作用。有人可以指导我如何在 Android 中完成此任务吗?
这是我在后台更新位置的基本位置服务:
class LocationService : Service() {
private val locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
locationResult ?: return
for (location in locationResult.locations) {
// do something with the location here
}
}
}
override fun onCreate() {
val locationRequest = LocationRequest().apply {
interval = 10000
fastestInterval = 5000
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
val client = LocationServices.getFusedLocationProviderClient(this)
val locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
locationResult ?: return
for (location in locationResult.locations) {
// do something with the location here
}
}
}
client.requestLocationUpdates(locationRequest, locationCallback, null)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return START_STICKY
}}
一种可能的解决方案是将 Transition API 与广播接收器结合使用。 Transition API 可以侦听活动的变化,例如设备何时开始移动,并在后台启动服务。此外,我们可以使用广播接收器来监听位置更新,并在设备位置改变 100 米或更多时重新启动服务。但是,我不确定这是否适用于应用程序被完全杀死的情况,并且需要有关如何正确实施此解决方案或您想到的任何其他解决方案的指导,以创建“防杀”位置跟踪服务。
【问题讨论】:
标签: android android-location android-broadcast android-transitions foreground-service