Does startService() create a new Service instance or using the existing one? For example, in the following code, does it create two UpdateService instances or just one UpdateService instance? Thanks.
int[] appWidgetIds = new int[] {1, 2}; for (int appWidgetId : appWidgetIds) { Intent intent = new Intent(context, UpdateService.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); context.startService(intent); }
Starting a service You can start a service from an activity or other application component by passing an Intent to startService() or startForegroundService() . The Android system calls the service's onStartCommand() method and passes it the Intent , which specifies which service to start.
The Service will only run in one instance. However, everytime you start the service, the onStartCommand() method is called. Thanks. It also says there: "The startService() method returns immediately and the Android system calls the service's onStartCommand() method.
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.
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.
If the service is already started, it does not start as second copy, but onStart()
is still called on the existing instance. Services are natural singletons -- there is exactly 0 or 1 copy of the service in operation.
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