Creating a started service
- A started service is one that another component starts by calling startService(), which results in a call to the service's onStartCommand() method.
- When a service is started, it has a lifecycle that's independent of the component that started it.
- The service can run in the background indefinitely, even if the component that started it is destroyed.
- As such, the service should stop itself when its job is complete by calling stopSelf(), or another component can stop it by calling stopService().
- An application component such as an activity can start the service by calling startService() and passing an Intent that specifies the service and includes any data for the service to use.
- The service receives this Intent in the onStartCommand() method.
- For instance, suppose an activity needs to save some data to an online database.
- The activity can start a companion service and deliver it the data to save by passing an intent to startService().
- The service receives the intent in onStartCommand(), connects to the Internet, and performs the database transaction.
- When the transaction is complete, the service stops itself and is destroyed.
Caution:
- A service runs in the same process as the application in which it is declared and in the main thread of that application by default.
- If your service performs intensive or blocking operations while the user interacts with an activity from the same application, the service slows down activity performance.
- To avoid impacting application performance, start a new thread inside the service.
Service Class
- The Service class is the base class for all services.
- When you extend this class, it's important to create a new thread in which the service can complete all of its work; the service uses your application's main thread by default, which can slow the performance of any activity that your application is running.
- The Android framework also provides the IntentService subclass of Service that uses a worker thread to handle all of the start requests, one at a time.
- Using this class is not recommended for new apps as it will not work well starting with Android 8 Oreo, due to the introduction of Background execution limits.
- Moreover, it's deprecated starting with Android 11.
- You can use JobIntentService as a replacement for IntentService that is compatible with newer versions of Android.
Extending the Service class
- You can extend the Service class to handle each incoming intent.
- Notice that the onStartCommand() method must return an integer.
- The integer is a value that describes how the system should continue the service in the event that the system kills it.
- The return value from onStartCommand() must be one of the following constants:
- START_NOT_STICKY
- If the system kills the service after onStartCommand() returns, do not recreate the service unless there are pending intents to deliver.
- This is the safest option to avoid running your service when not necessary and when your application can simply restart any unfinished jobs.
- START_STICKY
- If the system kills the service after onStartCommand() returns, recreate the service and call onStartCommand(), but do not redeliver the last intent.
- Instead, the system calls onStartCommand() with a null intent unless there are pending intents to start the service.
- In that case, those intents are delivered.
- This is suitable for media players (or similar services) that are not executing commands but are running indefinitely and waiting for a job.
- START_REDELIVER_INTENT
- If the system kills the service after onStartCommand() returns, recreate the service and call onStartCommand() with the last intent that was delivered to the service.
- Any pending intents are delivered in turn.
- This is suitable for services that are actively performing a job that should be immediately resumed, such as downloading a file.
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.
- For example:
- The startService() method returns immediately, and the Android system calls the service's onStartCommand() method.
- If the service isn't already running, the system first calls onCreate(), and then it calls onStartCommand().
- 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.
Note:
- If your app targets API level 26 or higher, the system imposes restrictions on using or creating background services unless the app itself is in the foreground.
- If an app needs to create a foreground service, the app should call startForegroundService().
- That method creates a background service, but the method signals to the system that the service will promote itself to the foreground.
- Once the service has been created, the service must call its startForeground() method within five seconds.
Stopping a service
- 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().
- Once requested to stop with stopSelf() or stopService(), the system destroys the service as soon as possible.
Creating a bound service
- A bound service is one that allows application components to bind to it by calling bindService() to create a long-standing connection.
- It generally doesn't allow components to start it by calling startService().
- Create a bound service when you want to interact with the service from activities and other components in your application or to expose some of your application's functionality to other applications through interprocess communication (IPC).
- To create a bound service, implement the onBind() callback method to return an IBinder that defines the interface for communication with the service.
- Other application components can then call bindService() to retrieve the interface and begin calling methods on the service.
- The service lives only to serve the application component that is bound to it, so when there are no components bound to the service, the system destroys it.
- You do not need to stop a bound service in the same way that you must when the service is started through onStartCommand().
- To create a bound service, you must define the interface that specifies how a client can communicate with the service.
- This interface between the service and a client must be an implementation of IBinder and is what your service must return from the onBind() callback method.
- After the client receives the IBinder, it can begin interacting with the service through that interface.
- Multiple clients can bind to the service simultaneously.
- When a client is done interacting with the service, it calls unbindService() to unbind.
- When there are no clients bound to the service, the system destroys the service.
Sending notifications to the user
- When a service is running, it can notify the user of events using Toast Notifications or Status Bar Notifications.
- A toast notification is a message that appears on the surface of the current window for only a moment before disappearing.
- A status bar notification provides an icon in the status bar with a message, which the user can select in order to take an action (such as start an activity).
- Usually, a status bar notification is the best technique to use when background work such as a file download has completed, and the user can now act on it.
- When the user selects the notification from the expanded view, the notification can start an activity (such as to display the downloaded file).
Managing the lifecycle of a service
- The lifecycle of a service is much simpler than that of an activity.
- However, it's even more important that you pay close attention to how your service is created and destroyed because a service can run in the background without the user being aware.
- The service lifecycle—from when it's created to when it's destroyed—can follow either of these two paths:
- A started service
- The service is created when another component calls startService().
- The service then runs indefinitely and must stop itself by calling stopSelf().
- Another component can also stop the service by calling stopService().
- When the service is stopped, the system destroys it.
- A bound service
- The service is created when another component (a client) calls bindService().
- The client then communicates with the service through an IBinder interface.
- The client can close the connection by calling unbindService().
- Multiple clients can bind to the same service and when all of them unbind, the system destroys the service. The service does not need to stop itself.
Important:
- These two paths aren't entirely separate.
- You can bind to a service that is already started with startService().
- For example, you can start a background music service by calling startService() with an Intent that identifies the music to play.
- Later, possibly when the user wants to exercise some control over the player or get information about the current song, an activity can bind to the service by calling bindService().
- In cases such as this, stopService() or stopSelf() doesn't actually stop the service until all of the clients unbind.
Implementing the lifecycle callbacks
Example:
public class ExampleService extends Service {
int startMode; // indicates how to behave if the service is killed
IBinder binder; // interface for clients that bind
boolean allowRebind; // indicates whether onRebind should be used
@Override
public void onCreate() {
// The service is being created
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The service is starting, due to a call to startService()
return startMode;
}
@Override
public IBinder onBind(Intent intent) {
// A client is binding to the service with bindService()
return binder;
}
@Override
public boolean onUnbind(Intent intent) {
// All clients have unbound with unbindService()
return allowRebind;
}
@Override
public void onRebind(Intent intent) {
// A client is binding to the service with bindService(),
// after onUnbind() has already been called
}
@Override
public void onDestroy() {
// The service is no longer used and is being destroyed
}
}
By implementing these methods, you can monitor these two nested loops of the service's lifecycle:
1. The entire lifetime of a service occurs between the time that onCreate() is called and the time that onDestroy() returns.
Like an activity, a service does its initial setup in onCreate() and releases all remaining resources in onDestroy().
For example, a music playback service can create the thread where the music is played in onCreate(), and then it can stop the thread in onDestroy().
Note: The onCreate() and onDestroy() methods are called for all services, whether they're created by startService() or bindService().
2. The active lifetime of a service begins with a call to either onStartCommand() or onBind().
Each method is handed the Intent that was passed to either startService() or bindService().
If the service is started, the active lifetime ends at the same time that the entire lifetime ends (the service is still active even after onStartCommand() returns).
If the service is bound, the active lifetime ends when onUnbind() returns.