我想在 Android 上编写一个应用程序,每 5 分钟将我的 GPS 位置上传到外部网站一次。这需要对电池寿命的影响尽可能小,但也需要在没有任何用户交互的情况下工作。 (背景:我正在参加铁人三项赛,大约需要 14 个小时才能完成,并且希望近乎实时地广播我的位置,但不必担心摆弄我的手机。)
所以我最初的想法是编写一个使用 LocationManager.requestLocationUpdates() 且 minTime 为 5 分钟的服务,但这实际上会每 5 分钟唤醒一次设备以便我的服务完成其工作吗?
听起来我还需要使用 AlarmManager.setInexactRepeating() 来确保我的服务在完成其任务时处于唤醒状态,但这如何与 requestLocationUpdates() 一起使用?我是否应该在 requestLocationUpdates() 上设置 minTime=0 但在获得下一个更新后立即返回睡眠状态?
非常感谢任何有关如何设计的一般指导。我是一名称职的 Java 程序员将在服务器上使用 Google 地图来绘制我的位置,但我对 Android 开发还很陌生,因此我基本上正在寻找有关如何构建客户端应用程序的高级计划。
I would like to write an app on Android to upload my GPS location to an external website once every ~5 minutes. This needs to have as minimal an impact on battery life as possible, but it also needs to work without any user interaction. (Background: I'm competing in an Ironman triathlon which will take me about 14 hours to complete, and want to broadcast my location in near-real-time but without having to worry about fiddling with my phone.)
So my initial thought is to write a Service which uses LocationManager.requestLocationUpdates() with a minTime of 5 minutes, but will this actually wake the device up every 5 minutes for my service to do its job?
It sounds like I would also need to use AlarmManager.setInexactRepeating() to make sure my service is awake while it completes its task but how does that play with requestLocationUpdates()? Should I instead set minTime=0 on requestLocationUpdates() but then go back to sleep as soon as the next update is obtained?
Any general guidance on how to design this is greatly appreciated. I'm a competent Java programmer & will be using Google Maps on the server to plot my location, but am pretty new to Android development so I'm basically looking for a high-level plan on how to architect the client app.
发布评论
评论(1)
您的服务必须始终处于活动状态以接收更新。
http://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates%28java.lang.String,%20long,%20float,%20android.location.LocationListener%29
您可以使用 minTime 参数来告知您希望多久收到一次位置更改通知。然而,它不会减少电池消耗。无论您希望多久接收一次更新,除非您使用removeUpdates 方法,否则GPS 都会启用。
您可以使用另一种方法:使用上面的方法启用GPS,读取一个值,使用removeUpdates方法,等待5分钟,然后重新开始。启用和检索位置之间的延迟可能在几秒钟到几分钟之间。
Your service must be alive all the time you want to receive updates.
http://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates%28java.lang.String,%20long,%20float,%20android.location.LocationListener%29
You can tell how often you want to be informed of location change with minTime parameter. It does not however decrease battery consumption. GPS is enabled unless you use removeUpdates method no matter how often you want to receive updates.
You can use another approache:enable GPS using method above, read one value, use removeUpdates method, wait 5 minutes and all over again. Delay between enabling and retreiving a location can be between few seconds to few minutes.