13

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???

pnuts
  • 58,317
  • 11
  • 87
  • 139
Manos Varesis
  • 145
  • 1
  • 1
  • 6

3 Answers3

20

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
7

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

Shayan Pourvatan
  • 11,898
  • 4
  • 42
  • 63
1

Multiple requests to start the service result in multiple corresponding calls to the service's onStartCommand(). However, only one request to stop the service (with stopSelf() or stopService()) is required to stop it.

Sample log below after starting the same service 3 times

.service D/HelloService: onCreate: 
.service D/HelloService: onStartCommand: 
.service D/HelloService: onStartCommand: 
.service D/HelloService: onStartCommand: 
.service D/HelloService: task: 
.service D/HelloService: task: 
.service D/HelloService: task: 
.service D/HelloService: onDestroy:

for more detail go for official doc below https://developer.android.com/guide/components/services.html#StartingAService

Neeraj Singh
  • 610
  • 9
  • 15