On click of a button I want to start service using method startService(new Intent(currentActivity.this,MyService.class))
but if service is running I don't want to call this method to avoid run service that is already running.How this is possible.I am using both Intent service and Service in same project and want to apply same condition for both.
If you call startService() multiple times, the service will be called with onStartCommand() multiple times, one per call to startService() . Whether it will "restart" will depend upon whether the service was still considered to be running from the previous startService() call.
To start the service, call startService(intent) and to stop the service, call stopService(intent) .
Stopping a service. You stop a service via the stopService() method. No matter how frequently you called the startService(intent) method, one call to the stopService() method stops the service. A service can terminate itself by calling the stopSelf() method.
A service will only run once, so you can call startService(Intent)
multiple times.
You will receive an onStartCommand()
in the service. So keep that in mind.
Source: Note that multiple calls to Context.startService()
do not nest (though they do result in multiple corresponding calls to onStartCommand()
), so no matter how many times it is started a service will be stopped once Context.stopService()
or stopSelf()
is called; however, services can use their stopSelf(int)
method to ensure the service is not stopped until started intents have been processed.
At: http://developer.android.com/reference/android/app/Service.html on topic: Service Lifecycle
Use startService()
. Start Service will call onStartCommand()
If the Service isn't started yet it will Call onCreate()
. Initialize your variables and/or start a Thread in onCreate()
.
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