Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you start the same service twice in Android?

I am developing an android app that has a button and two EditTexts. When the button is pressed, a service starts and the data from the two EditTexts pass to it. If the user changes the data and presses again the button, what will happen?? Will the service restart again with the new data??? Or will it create two services with different data???

like image 762
Manos Varesis Avatar asked Nov 18 '15 16:11

Manos Varesis


People also ask

Can we start a service multiple times in Android?

Absolutely Correct. Only one instance of Service is created for an application process.

What happens when you start a service in Android?

A started service must manage its own lifecycle. That is, the system doesn't stop or destroy the service unless it must recover system memory and the service continues to run after onStartCommand() returns. The service must stop itself by calling stopSelf() , or another component can stop it by calling stopService() .

How do I know if my Android service is running?

You can do this by making your own Interface where you declare for example " isServiceRunning() ". You can then bind your Activity to your Service, run the method isServiceRunning(), the Service will check for itself if it is running or not and returns a boolean to your Activity.

What are the return values of on Start command in Android services?

The documentation says: For backwards compatibility, the default implementation calls onStart(Intent, int) and returns either START_STICKY or START_STICKY_COMPATIBILITY. So returning super. onStartCommand() is equivalent to returning START_STICKY .


2 Answers

If the user changes the data and presses again the button, what will happen?

Presumably, the same thing that happened the first time. That is difficult to say for certain, since we do not have your source code.

Will the service restart again with the new data?

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. If something called stopService() or stopSelf() to stop the service, then a subsequent call to startService() will create a fresh instance of the service.

Or will it create two services with different data?

Services are natural singletons. There will be zero or one copy of your service running at any point.

like image 149
CommonsWare Avatar answered Oct 26 '22 15:10

CommonsWare


The Service will only run in one instance. However, everytime you start the service, the onStartCommand() method is called. you can read document from following link :

http://developer.android.com/guide/topics/fundamentals/services.html#StartingAService

like image 27
Shayan Pourvatan Avatar answered Oct 26 '22 15:10

Shayan Pourvatan