Android Service Introduction.

January 26, 2018 Oclemy Android Service 1 minute, 48 seconds

A service is an android application component that represents:

  1. An applications desire to perform long running operations while not interacting with the user.
  2. A component to supply functionality to other applications.

When should I use a Service?

Use a service if you have a long running operation or a task that has a long lifecycle. It's a good design that long running operations be executed in the background.

An example is a background data synchronization task.

In that type of task you can create a service that runs periodically or as needed. You can make use of a system alarm.

Then your service can terminate when the task is over.

Doing the job in the background frees up the main thread from having to do these tasks thus preventing the user interface from being frozen whenever an intensive tasks is being executed.

Even though we can just spin off a new thread even inside an activity, a much better and cleaner way is to delegate the background operations to a service.

Where does the Service run?

All android components, service included do run in the main thread of the application process.

Service's lifecycle is different from Activity's liefcycle. Th former is better adapted to handle long running operations than the latter.

Once we've moved our long running operations to a background thread, we can start and handle that thread inside the service.

Long running operations that don't require the user interactions are the best candidate for delegation to a service.

Advantages of a Service

  1. Service provides a more efficient mechanism for us to decouple long running operations from the user interface.

Example Usages of a Service

(a). Services without user input

  1. Apps that utilize network frequently to poll for updates.
  2. Music playing app.
  3. Messaging application.

(b). Services with user input

  1. Photo sharing app.

How do I use a Service

  1. Well, a Service is just a class that you subclass.
    public class MyService extends Service {|
  2. Being a class you can optionally give it a constructor:
    public MyService() {}
  3. Then you override the onBind() callback:
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

Comments