Wednesday 5 March 2014

Binding Services - part 2 (staying in the foreground)

In our previous tutorial we saw how to create a binding Service and how to bind to it using the Binder pattern. This is a very useful pattern because, once we retrieve a valid reference to our Service, we can use this reference to call Service's methods like any other Java object.



Binding Services usually stay alive until the last client disconnects, calling the unbindService method. When no more clients are connected, the Service is no longer running in the foreground and may be targeted by the system for shutdown (usually when Android is running out of resources).
In order to prevent the system from doing this, we can use the startForeground method. This method makes sure that the Service will stay in the foreground state (usually when executing long running tasks in the background) even if no client is connected.
The only thing to remember is to always call stopForeground, with the parameter true, when the Service has completed its task, otherwise we could potentially waste system resources.



Let's suppose to define a method in our Service class called executeTask, which is meant to perform long running operations. This method is called from our Activity, once a valid reference to our Service is obtained (see previous tutorial for more details), with the following code:

myService.executeTask();

Now we want that our Service will stay in the foreground until the task is completed. We also create a notification reporting that a background operation is running:

public void executeTask() {
   //create the Notification
   Notification.Builder builder = new Notification.Builder(this);
   builder.setContentTitle("Notification title");
   builder.setContentText("Notification text");
   builder.setSmallIcon(R.drawable.icon_for_notification);
   Notification mNotification = builder.build();

   //the Service won't be stopped by the system
   startForeground(1001, mNotification);

  //background operations: left out for brevity
  ...

  //remove the Service from foreground state
  stopForeground(true);
}

No comments:

Post a Comment