简体   繁体   English

Android,位置服务在后台

[英]Android, location Service in the background

There are tons of so threads on this topic and I've read Google's documentation and other stuff but still it's not clear for me how it is possible to get location updates, forever . 关于这个主题的话题如此之多,我已经阅读了Google的文档和其他内容,但对于我来说,仍然不清楚如何永远获得位置更新。

What I need : to know where a user is NOW (means: range 5-10 minutes) so every 5-10 minutes, IF there's a location updated, I need to store the new location in a db, even if the main app is not running. 我需要什么 :知道用户现在在哪里(意味着:5-10分钟),所以每5-10分钟,如果有一个位置更新,即使主应用程序是,我也需要将新位置存储在数据库中没有运行。

As far, I've done a never ending service that every 5-10 minutes asks for last location, but this (polling) is, obviously, not good. 到目前为止,我已经完成了一项永无止境的服务,每5-10分钟询问一次最后的位置,但是,这种(轮询)效果显然不好。

Google's latest Receiving Location Updates documentation shows how to do it in the MainActivity and nothing more. Google的最新“ 接收位置更新”文档显示了如何在MainActivity中执行此操作,仅此而已。

The IntentService , suggested by Google, " handles asynchronous requests (expressed as Intents) on demand " so it doesn't seem to be a right candidate. 由Google建议的IntentService按需处理异步请求(表示为Intent) ”,因此它似乎不是合适的人选。

Any kind of help would be appreciated. 任何帮助将不胜感激。

My main problem was " how to start the service after booting ", so I've solved in the following way: 我的主要问题是“ 启动后如何启动服务 ”,因此我通过以下方式解决了问题:

  • created a Service with a LocationListener. 使用LocationListener创建了一个服务。 It returns Service.START_REDELIVER_INTENT from the onStartCommand method. 它从onStartCommand方法返回Service.START_REDELIVER_INTENT
  • created a BroadcastReceiver that starts the Service after ther boot 创建了一个BroadcastReceiver,在启动后启动服务
  • in the manifest, moved android:installLocation="auto" to android:installLocation="internalOnly" to make the BroadcastReceiver work ( doc ) 在清单中,将android:installLocation="auto"移至android:installLocation="internalOnly"以使BroadcastReceiver正常工作( doc

Still, if the user closes the app from the settings ( Force close ), the service will stop working but this is what the user wants so, no problems. 尽管如此,如果用户从设置中关闭了该应用程序(“ Force close ),该服务将停止运行,但这正是用户想要的,没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM