Android:我可以使用广播接收器进行定期 GPS 位置采样而不运行服务吗?
我想定期(例如每 10 分钟)对我的 GPS 位置进行采样。我假设执行此操作的最佳方法是将 LocationManager 类与以下方法一起使用:
public void requestLocationUpdates (String provider, long minTime, float minDistance, PendingIntent intent)
这将广播指定的意图,然后我可以在应用程序的广播接收器中接收该意图。我的问题是,如果我从活动中调用此方法,当调用 requestLocationUpdate() 的进程被终止时广播是否会停止,或者此注册是否会保持活动状态以便我可以继续获取位置更新?当用户移动到不同的应用程序时,我是否需要保持服务运行才能保持位置更新?谢谢!
I would like to sample my GPS location periodically, say, every 10 minutes. I'm assuming that the best way to do this would be to use the LocationManager class with the method:
public void requestLocationUpdates (String provider, long minTime, float minDistance, PendingIntent intent)
That would broadcast the specified intent that I could then receive in a broadcast receiver in my application. My question is, if I call this method from an activity, will the broadcasts stop when the process that called the requestLocationUpdate() is killed, or will this registration remain active so that I can continue to get location updates? Do I need to leave a service running to be able to keep the location updates coming when a user moves to different applications? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,基本上你说的是正确的。
我认为即使
Activity
终止,注册也应该保持活动状态,因为您已向LocationManager
提供了PendingIntent
。不依赖于您的任务是否处于活动状态 -PendingIntent
包含框架所需的所有信息。来自文档:
应该非常简单。只需从您的 Activity 或服务中启动您的位置更新,然后进入 shell 并终止您的应用程序,看看 GPS 工具栏图标是否仍然存在,并且您是否按预期收到您的
Intent
。至于让
Service
保持运行,应该避免这种情况。您的PendingIntent
可以为您启动服务,让它处理传入位置Intent
,执行其必须执行的任何处理,然后自行停止 (Service.stopSelf( )
)。当LocationManager
触发下一个Intent
时,它将再次启动。只需确保您在某个时候取消注册接收位置更新即可!
Basically what you said is correct, as far as I'm aware.
I think the registration should remain active even if the
Activity
dies since you've provided aPendingIntent
to theLocationManager
. There is no dependency on your task being alive — thePendingIntent
contains all the info the framework needs.From the docs:
It should be pretty simple to test this out anyway. Just start your location updates from your activity or service, then go into the shell and kill off your app and see if the GPS toolbar icon remains and you receive your
Intent
as expected.As for leaving a
Service
running, this should be avoided. YourPendingIntent
can start the service for you, leaving it to handle the incoming locationIntent
, do whatever processing it has to and then stop itself (Service.stopSelf()
). It will be started again when the nextIntent
is fired by theLocationManager
.Just make sure that you unregister from receiving location updates at some point!