Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does startService() create a new Service instance or using the existing one?

Tags:

android

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);     } 
like image 332
user256239 Avatar asked Mar 25 '10 18:03

user256239


People also ask

What is the correct way to start a service in Android?

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.

What happens if I start a service in a loop?

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.

What happens when you start a service in Android?

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.

How to stop a 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.


1 Answers

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.

like image 71
CommonsWare Avatar answered Sep 20 '22 03:09

CommonsWare