In Android, service is a process which doesn’t need user interaction. It is a component which keep an app running in the background to perform long-running operations.

Types of Services

These are the three different types of services:

  • Foreground : A foreground service performs some operation that is noticeable to the user. When you use a foreground service, you must display a notification so that users are actively aware that the service is running. This notification cannot be dismissed unless the service is either stopped or removed from the foreground.
  • Background : A background service performs an operation that isn’t directly noticed by the user.
  • Bound : A service is bound when an application component binds to it by calling bindService(). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

Service Life Cycle

Life cycle of service will follow two different paths. 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. To stop the started service call stopService() method or the service can stop itself by calling stopSelf() method.

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. To unbind the service call unbindService() method.

Android Service Life Cycle

Create Service

To create a service, we need extends Service class or one of its existing subclasses. We must override some of the methods of the Service class. An activity can start the service by calling startService() which results in calling the service’s onStartCommand() method.

Following example create a service to play the ringtone.

public class MyService extends Service {

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        // Systems default ringtone
        player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);

        player.setLooping(true);
 
        // Start the player
        player.start();
 
        // Service will be explicity started and stopped
        return START_STICKY;
    }
 
 
    @Override
    public void onDestroy() {
        super.onDestroy();

        // Stopping the player
        player.stop();
    }
}

The return value from onStartCommand() must be one of the following constants:

  • START_NOT_STICKY : If the system kills the service after onStartCommand() returns, do not recreate the service unless there are pending intents to deliver.
  • START_STICKY : If the system kills the service after onStartCommand() returns, recreate the service and call onStartCommand(), but do not redeliver the last intent.
  • START_REDELIVER_INTENT : If the system kills the service after onStartCommand() returns, recreate the service and call onStartCommand() with the last intent that was delivered to the service. Any pending intents are delivered in turn.

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

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="co.mymusing.androidserviceexample">
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <!-- Defining the service class here --> 
        <service android:name=".MyService" />
    </application>
 
</manifest>

Starting and Stopping Service

Component such as an activity, service or receiver can start the service using startService() method. In the following example, a service is started by activity.

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button buttonStart;
    private Button buttonStop;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        buttonStart = (Button) findViewById(R.id.buttonStart);
        buttonStop = (Button) findViewById(R.id.buttonStop);
 
        buttonStart.setOnClickListener(this);
        buttonStop.setOnClickListener(this);
    }
 
    @Override
    public void onClick(View view) {

        if (view == buttonStart) {

            // Start service
            startService(new Intent(this, MyService.class));
        } else if (view == buttonStop) {

            // Stop service 
            stopService(new Intent(this, MyService.class));
        }
    }
}

Following is the layout file (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:orientation="vertical">
 
        <Button
            android:id="@+id/buttonStart"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Start Service" />
 
        <Button
            android:id="@+id/buttonStop"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Stop Service" />
 
    </LinearLayout>

</RelativeLayout>

To start the service, tap on Start Service and ringtone will start ringing. And even if you close your application ringtone will keep ringing. To stop the service, tap on Stop Service button. As we can see in the above example, we can trigger the execution of a service via the startService(intent) method.

To stop the service, call stopService() method. A service can terminate itself by calling the stopSelf() method. This is typically done if the service finishes its work.