Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 681
rickyalbert Avatar asked May 29 '14 17:05

rickyalbert


People also ask

What happens to service when activity is destroyed?

The service can run in the background indefinitely, even if the component that started it is destroyed. As such, the service should stop itself when its job is complete by calling stopSelf() , or another component can stop it by calling stopService() .

How do you stop a service from stopping on Android?

You may run the service in the foreground using startForeground(). A foreground service is a service that's considered to be something the user is actively aware of and thus not a candidate for the system to kill when low on memory.

When can Android activity be destroyed?

A: When you rotate the device, the activity is destroyed and a new one is created in its place.


2 Answers

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.

like image 64
Miguel Botón Avatar answered Oct 20 '22 13:10

Miguel Botón


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.

like image 6
CommonsWare Avatar answered Oct 20 '22 12:10

CommonsWare