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???
Absolutely Correct. Only one instance of Service is created for an application process.
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() .
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.
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 .
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.
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
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