Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to prevent service to run again if already running android

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.

like image 379
Atul Bhardwaj Avatar asked May 24 '12 14:05

Atul Bhardwaj


People also ask

What happens if we start a service twice android?

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.

How do I stop a service from activity?

To start the service, call startService(intent) and to stop the service, call stopService(intent) .

How can we stop service in Android?

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.


2 Answers

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

like image 116
Ion Aalbers Avatar answered Sep 19 '22 10:09

Ion Aalbers


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().

like image 39
Thijs Limmen Avatar answered Sep 18 '22 10:09

Thijs Limmen