带有 locationListener 回调的 Android 服务

标签 android service geolocation locationlistener

我有一个 Android 应用程序。根据用户当前的地理位置,我想在后台获取一些远程数据并存储它。我的实现是:

在特定的时间间隔,警报会启动我的服务。 Service 使用匿名类来查询当前位置并注册一个 locationListener 回调。在调用 onLocationChanged() 时,我启动从服务器获取远程数据。

但是,一旦我的服务使用 anonymos 类完成注册位置监听器,它就会按预期返回;因为它在完成之前不会等待回调发生。由于回调需要一些时间并在服务已经返回时进行调用,因此它会抛出一个错误:

java.lang.RuntimeException: Handler{43e82510} sending message to a Handler on a dead thread

这是很好理解的。现在对我来说一个快速的解决方法是我可以使用 locationManager 中的 getLastKnownLocation 因为它不会通过回调响应;但如果我现在确实想要最新的位置(在服务而不是 Activity 中)怎么办?我如何等待回调发生并停止我的服务返回。

此外,lastKnownlocation 在什么时候更新?每次 GPS 记录新位置时;它会更新吗?我想知道的是,如果不是最新的还能关闭到最新吗?因为我在 android 模拟器中没有看到配置后续更新之间的时间段的选项。

非常感谢任何帮助。 干杯

最佳答案

but what if I do want the latest location right now, in a service and not activity?

抱歉,但这在服务或 Activity 中都是不可能的。例如,如果 GPS radio 关闭,而您正在向 GPS 请求位置数据,则需要数十秒才能获得修复,如果您幸运的话。它可能根本无法得到修复。

How can I wait for callback to happen and stop my service from returning.

你不知道。你按照你说过的去做:

use getLastKnownLocation from locationManager as that doesn't respond back by callback

因此,让您的 Service(希望是 IntentService)检查 getLastKnownLocation() 是否恰好有值。如果有,请使用它。否则,registerLocationUpdates() 使用 PendingIntent 将控制权传递回您的 IntentService。当您得到那个 Intent 时,使用该位置并取消注册更新(假设警报周期很好而且很长,例如每小时一次)。

如果您的闹钟是 _WAKEUP 闹钟,事情就会变得棘手。然后,您需要按住 WakeLock,以便在您尝试获取 GPS 定位时设备不会重新进入休眠状态。但是,您需要在某个时候释放该 WakeLock,如果我们无法获得 GPS 修复...嗯...好吧,这就是棘手的部分。尝试找出一种干净利落的方法来处理此问题,并将其实现为可重用组件(例如 LocationAlarmService),是我的待办事项列表中的 18,000 项任务之一。

Also, at what point does lastKnownlocation gets updated? Everytime GPS registers a new location; does it > update it?

据我所知,是的。

关于带有 locationListener 回调的 Android 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3743474/

相关文章:

android - 了解 Android XML @ 前缀

android - 使用服务的 TCP 连接

android - 媒体服务 Activity

android - 地理位置跟踪和 Google Cloud Messaging 协同工作

android - map.setMyLocationEnabled(true) 的真正作用是什么

Android - Sprite 和线程理解问题

android - 如何使微调器宽度与最大可用项目宽度相同

Android:使用 android.provider.Telephony.Sms.Conversations

web-services - 语音识别(网络)服务?

c# - 使用缠绕数点在多边形中