Froskoy
Froskoy

Reputation: 3027

Service lifecycle in Android

I have a service in my Android application that needs to continue listening for location updates after the user has exited the application (the implications of this on battery life are a separate matter).

I'm not sure that I have correctly understood the lifecycle of a service in Android, outlined on this page:

http://developer.android.com/reference/android/app/Service.html

I believe if it returns START_STICKY in the onStart() method then the service will continue to run after the main application has quit regardless of whether or not the service is running in its own process. If the service is running in the same process as the rest of the app and I have understood correctly, the main app's process is kept alive after the app exits, just to run that service. When the app starts again, it will run in the same process as the service, which is still running. If the system gets low on memory, Android may decide to kill this service.

Secondly, I believe it is OK to run the location listener listening for GPS updates in the same process and indeed same thread as the rest of the application and it will not block when waiting for updates from the GPS.

Have I understood correctly?

Upvotes: 3

Views: 1474

Answers (2)

hitesh141
hitesh141

Reputation: 943

The actual life cycle of Service is described here by image. You run whatever service in android the life cycle if always follow like this.

enter image description here

Upvotes: 1

Timmetje
Timmetje

Reputation: 7694

You have understood correctly.

If the system gets low on memory, Android may decide to kill this service.

If you want it to be persistent you can create persisitent service (but it needs to be a system app / service).

Please use AlarmManager and an IntentService, so your service does not need to be in memory except when it is doing meaningful work. This also means Android is rather unlikely to kill your service while you are in memory, and users are unlikely to kill your service because they think you are wasting memory.

For your location Listener:

Use the Location Listener implemented in a service.

Start listening the GPS when the service starts and remove the GPS listener when the service stops.

Start this service when you wants to listen to GPS(every 10 minutes for example).

This is cleaner than having a service you try to continuously run and checking for Location changes.

Secondly, I believe it is OK to run the location listener listening for GPS updates in the same process and indeed same thread as the rest of the application and it will not block when waiting for updates from the GPS.

You do not need to setup a AsyncTask or background thread for this. Also understood correctly.

Upvotes: 4

Related Questions