简体   繁体   English

在服务或Android活动中注册位置更新更好吗?

[英]Is it better to register for Location updates in Service or in Activity for Android?

In one of the application that I am developing I am registering for location updates in a Service. 在我正在开发的一个应用程序中,我正在服务中注册位置更新。 Is that a better way of doing that? 这是更好的方法吗? The application logic is as such that the Service will be active till the application. 这样,应用程序逻辑将使服务在应用程序之前一直处于活动状态。

I have faced problem sometimes that, say once the service was running and location updates was working properly. 有时我遇到问题,例如,一旦服务运行且位置更新正常工作。 But after about 4-5 hours the location update stopped automatically, so it makes me believe that the Service is automatically stopped by the system after some time has elapsed. 但是大约4-5个小时后,位置更新会自动停止,因此我相信一段时间后系统会自动停止服务。 Please correct me if I am wrong over here. 如果我在这里错了,请纠正我。

In this case then I will have to register the location listener from activity rather than Service. 在这种情况下,我将不得不从活动而非服务中注册位置侦听器。 Can someone tell me whether I am understanding it correctly or not? 有人可以告诉我我是否正确理解它?

But after about 4-5 hours the location update stopped automatically, so it makes me believe that the Service is automatically stopped by the system after some time has elapsed. 但是大约4-5个小时后,位置更新会自动停止,因此我相信一段时间后系统会自动停止服务。

This sounds like the onStartCommand() needs to return START_STICKY , this should keep your service around untill it is explicitly stopped (make sure your users know that this constantly running service will cause an increased drain on the battery, depending on what all your service does). 这听起来像onStartCommand()需要return START_STICKY ,这应该使您的服务一直保持到明确停止为止(请确保您的用户知道此持续运行的服务会增加电池的电量,具体取决于您执行的所有服务) )。

In this case then I will have to register the location listener from activity rather than Service. 在这种情况下,我将不得不从活动而非服务中注册位置侦听器。

When any listener is registered within the context of an Activity the listener will only operate correctly while the Activity has user focus (see Managing the Application Lifecycle ). 在Activity的上下文中注册了任何侦听器后,该侦听器将仅在该Activity具有用户焦点时才能正确运行(请参阅管理应用程序生命周期 )。 When your Activity is paused or killed, so is your listening; 当您的活动被暂停或杀死时,您的聆听也将停止; a remote Service is a better choice. 远程服务是更好的选择。

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

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