Home  >  Blog  >   Android

Background Services In Android

Rating: 4
  
 
2968

A Service is an application component representing either an application’s desire to perform a long-running operation while not interacting with the user or to supply functionality for other applications to use. Each service class must have a corresponding declaration in its package’s AndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().

Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which it works. The IntentService class is available as a standard implementation of Service that has its own thread where it schedules its work to be done.

If you would like to Enrich your career with a  Android certified professional, then visit Mindmajix -A Global online training platform:  “Android Training  Course.  This course will help you to achieve excellence in this domain.

What is a Service?

More confusion about the Service class actually revolves around what it is not:

  • A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.

  • A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

Thus a Service itself is actually very simple, providing two main features:

  • A facility for the application to tell the system about something it wants to do in the background (even when the user is not directly interacting with the application). This corresponds to calls to Context.startService(), which asks the system to schedule work for the service, to be run until the service or someone else explicitly stops it.

  • A facility for an application to expose some of its functionality to other applications. This corresponds to calls to bindService(), which allows a long-standing connection to be made to the service in order to interact with it.

When a Service component is actually created, for either of these reasons, all that the system actually does is instantiate the component and call its onCreate() and any other appropriate callbacks on the main thread. It is up to the Service to implement these with the appropriate behavior, such as creating a secondary thread in which it does its work.

Note that because Service itself is so simple, you can make your interaction with it as simple or complicated as you want: from treating it as a local Java object that you make direct method calls on (as illustrated by Local Service Sample), to provide a full removable interface using AIDL.

MindMajix Youtube Channel

Checkout:-Android Services

Service Lifecycle

There are two reasons that a service can be run by the system. If someone calls Context.startService(), then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure that the service is not stopped until started intents have been processed.

For started services, there are two additional major modes of operation, they can decide to run in, depending on the value they return from onStartCommand(): START_STICKY is used for services that are explicitly started and stopped as needed, while START_NOT_STICKY or START_REDELIVER_INTENT are used for services that should only remain running while processing any commands sent to them.

Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand(). The client will receive the IBinder object that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the service’s IBinder). Usually, the IBinder returned is for a complex interface that has been written in aidl.

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service’s onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy().

Permissions   

Global access to a service can be enforced when it is declared in its manifest’s tag. By doing so, other applications will need to declare a corresponding element in their own manifest to be able to start, stop, or bind to the service.

In addition, a service can protect individual IPC calls into it with permissions, by calling the checkCallingPermission(String) method before executing the implementation of that call.

Process Lifecycle

The Android system will attempt to keep the process of hosting a service around as long as the service has been started or has clients bound to it. When running low on memory and needing to kill existing processes, the priority of a process hosting the service will be higher of the following possibilities:

  • If the service is currently executing code in its onCreate(), onStartCommand(), or onDestroy() methods, then the hosting process will be a foreground process to ensure this code can execute without being killed.

  • If the service has been started, then its hosting process is considered to be less important than any processes that are currently visible to the user on-screen, but more important than any process not visible. Because only a few processes are generally visible to the user, this means that the service should not be killed except in extreme low memory conditions.

  • If there are clients bound to the service, then the service’s hosting process is never less important than the most important client. That is, if one of its clients is visible to the user, then the service itself is considered to be visible.

  • A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory.

Checkout Android Interview Questions

Note this means that most of the time your service is running, it may be killed by the system if it is under heavy memory pressure. If this happens, the system will later try to restart the service. An important consequence of this is that if you implement onStartCommand() to schedule work to be done asynchronously or in another thread, then you may want to use START_FLAG_REDELIVERY to have the system re-deliver an Intent for you so that it does not get lost if your service is killed while processing it.

Other application components running in the same process as the service (such as an Activity) can, of course, increase the importance of the overall process beyond just the importance of the service itself.

Local Service Sample

One of the most common uses of a Service is as a secondary component running alongside other parts of an application, in the same process as the rest of the components. All components of an .apk run in the same process unless explicitly stated otherwise, so this is a typical situation.

When used in this way, by assuming the components are in the same process, you can greatly simplify the interaction between them: clients of the service can simply cast the IBinder they receive from it to a concrete class published by the service.

An example of this use of a Service is shown here. First is the Service itself, publishing a custom class when bound:

public class LocalService extends Service { 
private NotificationManager mNM;
// Unique Identification Number for the Notification.
// We use it on Notification start, and to cancel it.
private int NOTIFICATION = R.string.local_service_started;
public class LocalBinder extends Binder { 
LocalService getService() {
return LocalService.this;
}
}    public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting. We put an icon in the status bar. showNotification();
}
public int onStartCommand(Intent intent, int flags, int startId) { Log.i("LocalService", "Received start id " + startId + ": " + intent);
//We want this service to continue running until it is explicitly
//stopped, so return sticky.
return START_STICKY;
}
public void onDestroy() {
//Cancel the persistent notification. 
mNM.cancel(NOTIFICATION);
//Tell the user we stopped.
Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
}
public IBinder onBind(Intent intent) { 
return mBinder;
}
//This is the object that receives interactions from clients. See
//RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();
/** 
*Show a notification while this service is running.
*/
private void showNotification() {
//In this sample, we'll use the same text for the ticker and the expanded notification CharSequence text = getText(R.string.local_service_started);
//Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.stat_sample, text,
System.currentTimeMillis());
//The PendingIntent to launch our activity if the user selects this notification PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, LocalServiceActivities.Controller.class), 0);
//Set the info for the views that show in the notification panel. notification.setLatestEventInfo(this, getText(R.string.local_service_label),
text, contentIntent);
//Send the notification.
mNM.notify(NOTIFICATION, notification);
}
}

With that done, one can now write client code that directly accesses the running service, such as:

private LocalService mBoundService;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
//This is called when the connection with the service has been //established, giving us the service object we can use to 
//interact with the service. Because we have bound to an explicit //service that we know is running in our own process, we can
//cast its IBinder to a concrete class and directly access it. mBoundService = ((LocalService.LocalBinder)service).getService();
//Tell the user about this for our demo. Toast.makeText(Binding.this, R.string.local_service_connected,
Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) { // This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
//Because it is running in our same process, we should never 
//see this happen.
mBoundService = null;
Toast.makeText(Binding.this, R.string.local_service_disconnected,
Toast.LENGTH_SHORT).show();
}};
void doBindService() {
//Establish a connection with the service. We use an explicit
//class name because we want a specific service implementation that
//we know will be running in our own process (and thus won't be
//supporting component replacement by other applications). bindService(new Intent(Binding.this,
LocalService.class), mConnection, Context.BIND_AUTO_CREATE); mIsBound = true;
}
void doUnbindService() { if (mIsBound) {
// Detach our existing connection.
 
unbindService(mConnection); 
mIsBound = false;
}
}
@Override
protected void onDestroy() 
{ super.onDestroy(); 
doUnbindService();
}


Remote Messenger Service Sample

If you need to be able to write a Service that can perform complicated communication with clients in remote processes (beyond simply the use of Context.startService to send commands to it), then you can use the Messenger class instead of writing full AIDL files.

An example of a Service that uses Messenger as its client interface is shown here. First is the Service itself, publishing a Messenger to an internal Handler when bound:

public class MessengerService extends Service { 
/** For showing and hiding our notification. */ 
NotificationManager mNM;
/** Keeps track of all current registered clients. */ ArrayList mClients = new 
ArrayList(); /** Holds last value set by a client. */
int mValue = 0;
static final int MSG_REGISTER_CLIENT = 1; 
static final int MSG_UNREGISTER_CLIENT = 2;
static final int MSG_SET_VALUE = 3; 
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) 
{ switch (msg.what) {
case MSG_REGISTER_CLIENT: 
mClients.add(msg.replyTo); 
break;
case MSG_UNREGISTER_CLIENT:
mClients.remove(msg.replyTo);
break;
case MSG_SET_VALUE: 
mValue = msg.arg1;
for (int i=mClients.size()-1; i>=0; i--) { 
try {
mClients.get(i).send(Message.obtain(null, 
MSG_SET_VALUE, mValue, 0));
} catch (RemoteException e) {
//The client is dead. Remove it from the list;
//we are going through the list from back to front
//so this is safe to do inside the loop.
mClients.remove(i);
}
}
break;
default:
super.handleMessage(msg);
}         }     }
/**
* Target we publish for clients to send messages to IncomingHandler.
 */
final Messenger mMessenger = new Messenger(new IncomingHandler());
@Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us 
starting. showNotification();
}
@Override
public void onDestroy() {
//Cancel the persistent notification. mNM.cancel(R.string.remote_service_started);
//Tell the user we stopped.
Toast.makeText(this, R.string.remote_service_stopped, Toast.LENGTH_SHORT).show();
}
/**
*When binding to the service, we return an interface to our messenger
*for sending messages to the service.
*/
@Override
public IBinder onBind(Intent intent) { 
return mMessenger.getBinder();
}
/**
* Show a notification while this service is running. 
*/
private void showNotification() {
//In this sample, we'll use the same text for the ticker and the expanded notification CharSequence text = getText(R.string.remote_service_started);
//Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.stat_sample, text,
System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, Controller.class), 0);
//Set the info for the views that show in the notification panel. notification.setLatestEventInfo(this, getText(R.string.remote_service_label), text, contentIntent);
//Send the notification.
//We use a string id because it is a unique number. We use it later to cancel. mNM.notify(R.string.remote_service_started, notification);
}

If we want to make this service run in a remote process (instead of the standard one for its .apk), we can use android: process in its manifest tag to specify one:

Note that the name “remote” chosen here is arbitrary, and you can use other names if you want additional processes. The ‘:’ prefix appends the name to your package’s standard process name.

With that done, clients can now bind to the service and send messages to it. Note that this allows clients to register with it to receive messages back as well:

/** Messenger for communicating with service. */ 
Messenger mService = null;
/** Flag indicating whether we have called bind on the service. */ boolean mIsBound;
/** Some text view we are using to show state information. */ TextView mCallbackText;
/**
* Handler of incoming messages from service. 
*/
class IncomingHandler extends Handler 
{ @Override
public void handleMessage(Message msg) 
{ switch (msg.what) {
case MessengerService.MSG_SET_VALUE:
mCallbackText.setText("Received from service: " + 
msg.arg1); break;
default:
super.handleMessage(msg);
}    }}
/**
* Target we publish for clients to send messages to IncomingHandler. */
final Messenger mMessenger = new Messenger(new IncomingHandler());
/**
* Class for interacting with the main interface of the service. */
private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className,
IBinder service) {
//This is called when the connection with the service has been
//established, giving us the service object we can use to
//interact with the service. We are communicating with our
//service through an IDL interface, so get a client-side
//representation of that from the raw service object. mService = new Messenger(service); mCallbackText.setText("Attached.");
//We want to monitor the service for as long as we are
//connected to it.
try {
Message msg = Message.obtain(null,
MessengerService.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger; mService.send(msg);
//Give it some value as an example. msg = Message.obtain(null,
MessengerService.MSG_SET_VALUE, this.hashCode(), 0); mService.send(msg);
} catch (RemoteException e) {
//In this case the service has crashed before we could even
//do anything with it; we can count on soon being
//disconnected (and then reconnected if it can be restarted)
//so there is no need to do anything here.
}
// As part of the sample, tell the user what happened. Toast.makeText(Binding.this, R.string.remote_service_connected,
Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) { // This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed. mService = null; 
mCallbackText.setText("Disconnected.");
// As part of the sample, tell the user what happened. Toast.makeText(Binding.this, R.string.remote_service_disconnected,
Toast.LENGTH_SHORT).show();
}
};
void doBindService() {
//Establish a connection with the service. We use an explicit
//class name because there is no reason to be able to let other
//applications replace our component.
bindService(new Intent(Binding.this,
MessengerService.class), mConnection, Context.BIND_AUTO_CREATE); mIsBound = true;
mCallbackText.setText("Binding.");
}
void doUnbindService() { 
if (mIsBound) {
//If we have received the service, and hence registered with
//it, then now is the time to unregister.
if (mService != null) { 
try {
Message msg = Message.obtain(null,
MessengerService.MSG_UNREGISTER_CLIENT);
msg.replyTo = mMessenger; mService.send(msg);
} catch (RemoteException e) {
//There is nothing special we need to do if the service
//has crashed.
}}
//Detach our existing connection. unbindService(mConnection); mIsBound = false; mCallbackText.setText("Unbinding.");
}
}
Explore Android Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

 

Join our newsletter
inbox

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
NameDates
Android TrainingMar 30 to Apr 14View Details
Android TrainingApr 02 to Apr 17View Details
Android TrainingApr 06 to Apr 21View Details
Android TrainingApr 09 to Apr 24View Details
Last updated: 03 Apr 2023
About Author

Ravindra Savaram is a Technical Lead at Mindmajix.com. His passion lies in writing articles on the most popular IT platforms including Machine learning, DevOps, Data Science, Artificial Intelligence, RPA, Deep Learning, and so on. You can stay up to date on all these technologies by following him on LinkedIn and Twitter.

read more
Recommended Courses

1 / 15