简体   繁体   中英

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. 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.

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).

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 ). When your Activity is paused or killed, so is your listening; a remote Service is a better choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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