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
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() .
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.
A: When you rotate the device, the activity is destroyed and a new one is created in its place.
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.
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"
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With