rickyalbert
rickyalbert

Reputation: 2652

android - service stops when activity is destroyed

when I open the activity of my project I call the startService(Intent intent) method to start a new Service. When the activity is destroyed the service shouldn't be killed (because I didn't use the bindService() method), but the fact is that when I close my activity the service is killed and after a second the system creates a new Service (I verified that, the system calls again the onCreate() method of my service). What do I have to do to keep only one service ? Thank you

Upvotes: 15

Views: 22696

Answers (3)

Payam Hesami
Payam Hesami

Reputation: 97

Edit: Please refer to CommonsWare's answer

Old answer: You should override public int onStartCommand(Intent intent, int flags, int startId) method and return START_STICKY value as the mode of your service.

this will keeps your service working when the activity is destroyed or even when you exit your app unless you call stopService(Intent) explicitly

Upvotes: 0

Miguel Botón
Miguel Botón

Reputation: 766

To have a service running independently of your application's main process and to be sure that Android does not kill it while it's doing something, there are two things you should do/try.

  1. Run your service in a separate process. You can achieve this by adding the following attribute to your service declaration in the manifest:

    android:process=":somenamehere"

  2. When your service is running and you do not want it to be killed by the OS, you have to use the startForeground(int id, Notification notification) method. When the service finishes whatever is doing and can be killed by the OS, call stopForeground(boolean removeNotification). "startForeground" requires a notification as argument because every foreground service must display a notification so the user realizes about it

I hope this helps you.

Upvotes: 24

CommonsWare
CommonsWare

Reputation: 1007534

I mean I hold the home button and then kill my activity from the list of app open

That does not "close" an activity. That terminates your process. The user is welcome to terminate your process whenever the user wants, whether via this means or through third-party task manager apps. There is nothing you can do about this -- you cannot stop the user from terminating your process. Since your process will stop for other reasons as well (e.g., sheer old age), you have plenty of reasons to handle this case.

Upvotes: 6

Related Questions