Android Services

In android, Service is a component which keep an app running in the background to perform long-running operations based on our requirements. For Service, we don’t have any user interface and it will run the apps in the background like playing the music in the background or handle network operations when the user in a different app.

Android Service Life Cycle

In android, the life cycle of service will follow two different paths Started or Bound.

Started Service

A service is Started when an application component, such as an activity calls startService() method. Once it started, it will run indefinitely in background even if the component that started is destroyed.

We can stop the Started service by using stopService() method or the service can stop itself by calling stopSelf() method. In android, the Started service component will perform a single operation and it won’t return any result to the caller. 

Bound Service

A service is Bound when another application component calls bindService() method. The bound service runs as long as another application component is bound to it.

We can unbind the service by calling unbindService() method based on our requirements. In android, we can bind multiple components to a single service at once, but the service will be destroyed in case all the components unbind.

Android Services Lifecycle Diagram

Following diagram shows the lifecycle of Started service, when the service created with startService() and the lifecycle of Bound service, when the service created with bindService().

To create a service, we need to create a class that extends a Service base class or one of its existing subclasses. During our service implementation, we must need to override some of the callback methods that handle the key aspects of the service lifecycle and provide the functionality that allows our components to bind to the service.

Create a Service

Generally, in android to create a service we must create a subclass of Service or use one of existing subclass. In android the application component such as an activity can start the service by calling startService() which results in calling the service’s onStartCommand() method.

Following is the simple example of creating a service in android application.

public class SampleService extends Service {
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //TODO write your own code
        return Service.START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        //TODO for communication return IBinder implementation
        return null;
    }
}

Register a Service in Manifest File

Once we create a service, we need to register that in android manifest file using <service> element like as shown below.

<manifest ... >
...
  <application ... >
     <service android:name=".SampleService" />
  </application>
...
</manifest>

Start a Service

In android, the component such as an activity, service or receiver can start the service using startService() method. Following is the sample code snippet of starting a service using the startService method.

Intent intent = new Intent(this, MyService.class);
startService(intent);

Android Service Callback Methods

During the service implementation, following are the callback methods that we need to override in android application.

onStartCommand()

The system will invoke this method when another component such as an activity requests the service to be started by calling startService(). When this method executed, the service will start and run indefinitely in background. If we implement this in our code, it’s our responsibility to stop the service once code execution is done by calling stopSelf() or stopService() methods. In case, if we want to provide only binding, then we don’t need to implement this method.

In android, onStartCommand() method must return an integer and the integer is a value that describes how the system will continue the service in the event that the system kills it.

The onStartCommand() method will return a value from one of the following constants.

OptionDescription
START_STICKYIt will restart the service in case if it terminated and the Intent data which is passed to the onStartCommand() method is NULL. This is suitable for the service which are not executing commands but running independently and waiting for the job.
START_NOT_STICKYIt will not restart the service and it is useful for the services which will run periodically. The service will restart only when there are a pending startService() calls. It’s the best option to avoid running a service in case if it is not necessary.
START_REDELIVER_INTENTIt’s same as STAR_STICY and it recreates the service, call onStartCommand() with last intent that was delivered to the service.

onBind()

The system will invoke this method when another component wants to bind with the service by calling bindService(). During implementation of this method, we must need to provide an interface to the clients to communicate with the service by returning an IBinder object. In android, we must need to implement this method, in case if we don’t need to allow binding, then we should return NULL.

onCreate()

The system will invoke this method when the service is created initially using onStartCommand() or onBind() methods to do one-time setup procedures. In case, if the service is already running, then this method will not call.

onDestroy()

The system will invoke this method when the service is no longer used and is being destroyed. This is the final call that the service will receive and we need to implement this method in our service to clean up any unused resources such as threads, receivers or listeners.

Generally, in android if we start a service by calling startService() method, the service will run continuously even if the component that started service is destroyed until we stop it by using stopService() or it stops itself with stopSelf().

Same way, if we create a service by calling bindService() method, the service will runs as long as the component is bound to it. After the service is unbound from all of its clients, the system will destroy it.

In android, the service life cycle is having a set of callback methods that need to be implemented to keep a track of services status and to execute the required things in appropriate-time.

Android Skeleton Service

Following is the skeleton service that describes about each of the lifecycle methods.

package in.codingtimes.services;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class SampleService extends Service {
    int mStartMode;     // It indicates how to behave if the service is killed
    IBindermBinder;      // interface for clients that bind
    boolean mAllowRebind; // It 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 mStartMode;
    }
    @Override
    public IBinder onBind(Intent intent) {
        // A client is binding to the service with bindService()
        return mBinder;
    }
    @Override
    public boolean onUnbind(Intent intent) {
        // All clients have unbound with unbindService()
        return mAllowRebind;
    }
    @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
}
}

Android Services Example

Create an Application to create Services.

Following is the example of start playing music in the background when we start a service and that music will play continuously until we stop the service in the android application.

Now we need to create our own custom service file MyService.java in \java\in.codingtimes.services path to define our actual provider and associated methods for that right-click on your application folder  Go to New  select Java Class and give name as MyService.java.

Once we create a new file MyService.java, open it and write the code like as shown below

MyService.java

package in.codingtimes.services_android;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class MyService extends Service {

    private MediaPlayer player;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        player = MediaPlayer.create( this, Settings.System.DEFAULT_RINGTONE_URI );
        player.setLooping( true );
        player.start();
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        player.stop();
        Toast.makeText(this, "Service Stop", Toast.LENGTH_LONG).show();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Now open activity_main.xml file from \src\main\res\layout path and write the following code.

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/btnStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="startService"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="150dp"
        android:text="Start Service"
        android:backgroundTint="@color/teal_700"/>
    <Button
        android:id="@+id/btnStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="stopService"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="60dp"
        android:text="Stop Service"
        android:backgroundTint="@color/black"/>
</LinearLayout>

Now open MainActivity.java file from \java\in.codingtimes.services path and write following to implement custom broadcast intents.

MainActivity.java

package in.codingtimes.services_android;

import androidx.appcompat.app.AppCompatActivity;

        import android.content.Intent;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button btnStart,btnStop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStart = findViewById(R.id.btnStart);
        btnStop = findViewById(R.id.btnStop);

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startService(new Intent(MainActivity.this,MyService.class));
            }
        });

        btnStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stopService(new Intent(MainActivity.this,MyService.class));
            }
        });
    }
}

Now we need to register our service in android manifest file (AndroidManifest.xml) using <service> attribute like as shown below.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.codingtimes.services_android">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Services_Android">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyService" />
    </application>

</manifest>

Output of Android Service Example

When we run above example in android emulator we will get a result like as shown below

If we click on Start Service button, the default ringtone will start playing and it will continue until we stop the service. This is how we can create, start or stop services in android applications based on our requirements.

That’s it!
You have successfully completed the post. Do Share : )

Peace Out!

Also Read – Android AsyncTask


Check Out Deals on -> Amazon , Flipkart , Myntra , Adidas , Apple TV , Boat , Canva , Beardo , Coursera , Cleartrip , Fiverr , MamaEarth , SwiggyKFC


One comment

Leave a Reply

Your email address will not be published.