Using Services in android for background tasks

Updated 8 February 2016

Save

Android provides Services is a component that runs in the background without any user interaction or interface.

On the other  side, Activities have the graphical interface. Services run invisibly, performs long running tasks – doing Internet-related tasks, playing music, triggering notifications etc.
Services run with a higher priority than activities and Android system terminates them for resource management in rare cases.

The only reason Android will stop a Service prematurely is to provide additional resources for a foreground component usually an Activity. When this happens, Service can be configured to restart automatically.

 

States of Services:

Started
A Service starts by calling  startService(). Once service started, it can run in the background without time limit, even if the component that started it is destroyed.

Bound
A service is “bound”  by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results.

 

Lifecycle of Services:

A system can run a Service, If we call Context.startService() or bindService() method.

onStartCommand()
This method is called when the service is started, by calling startService(). Once this method executes, the service is started and can run in the background without time limit until its task not finished. It is our responsibility to stop the service when its work is done, by calling stopSelf() or stopService(). If we are defining our service as, bounded service then we don’t need to implement this method.

onBind()
We need to override this method, only if we are defining our service as bounded service.

onCreate()
This method is called while the service is first created.

onDestroy()
This method cleans up any resources such as threads, registered listeners, receivers, etc. This is the last call the service receives.

 

Example:

We need to perform some mandatory steps as follows:

Step 1:

As we declare activity and Broadcast Reciever in the manifest file, we must declare all services in our application’s manifest file.

To declare service, add an <service> element as a child of the <application> element. For example:

Step 2:

Now, we need to create a simple class and extends Service class-

Step 3:

It’s time to starting  a Service by startService()

Step 4:

This step is performed if required or on the basis of Service starting process-

We stop a service using the stopService() method. No matter how frequently we called the startService(i) method, one call to the stopService() method stops the service.

 

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home