how to prevent service to run again if already running android

Atul Bhardwaj picture Atul Bhardwaj · May 24, 2012 · Viewed 37.8k times · Source

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.

Answer

Ion Aalbers picture Ion Aalbers · May 24, 2012

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