but what if I do want the latest location right now, in a service and not activity?
抱歉,无论是服务还是活动都无法做到这一点.例如,如果GPS无线电关闭,并且您正在从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
因此,让您的服务(希望是一个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?
AFAIK,是的.