How To Create, Start, Stop Android Background Service

Android background service is an android component that runs in the background. There is no GUI for users to interact with the android background service object directly, it is usually started in android activity and runs in the same thread of the activity. When users quit the android-activity, the android background service will also exit automatically. This article introduces how to create, start, stop android background service with examples.

1. How To Create Android Background Service In Android Studio.

  1. Start android studio and right-click the package name in the android studio left project panel.
  2. Click the menu item New —> Service —> Service.
  3. Give the android background service a name by input its name in the next New Android Component window Class Name input box, check both the Exported and Enabled checkbox. If you check the Exported checkbox, then this service component can be invoked by other android apps besides the current android app. If you check the Enabled checkbox then this service component is enabled to be used by other android apps.
  4. When you click the Finish button in the above window, it will create the android background service class that extends It will also add the service object configuration XML data in AndroidManifest.xml file as below.

2. Android Background Service Methods.

If you want to customize the android background service component, you need to override the below methods.

  1. onCreate : When the service object is created, it will run this method. This method runs only once.
  2. onStartCommand : This method is invoked every time when the background service is started. You can execute tasks or start child threads in this method. Because the android background service is executed in the main activity thread, so if you do not use child threads and if the task is very time-consuming, the android activity main thread will be blocked by the service object.
  3. onDestroy : This method is invoked when the background service is destroyed. You can release related resources in it such as close database connection, write data to file, etc.
  4. stopSelf : If you want to stop and exit the running service in your source code, you can call this method.

3. How To Start Stop Android Background Service In Activity.

  1. If you want to start an android background service in an android activity, you can run the below source code.
    # Create an intent object, pass the activity instance and the service class to the constructure. 
    Intent intent = new Intent(Activity.this, MyBackgroundService.class);
    # Call startService method to start the background service.
  2. Call stopSerivce(intent) method to stop the service.
    Intent intent = new Intent(Activity.this, MyBackgroundService.class);
  3. If you want to make sure the background service is running after you start it, you can go to Settings —> Developer options —> Running services to see it.
  4. If you want to see the running andriod service in a terminal, you can run the below shell command to list all the running android services.
    adb shell service list
  5. If you want to list the android service by its name, you can run the below shell command.
    C:\Users\Jerry>adb shell dumpsys activity services ServiceName ( AudioService);

    The result like below:

    User 0 active services:
     * ServiceRecord{8b7857c u0 com.dev2qa.example/.audio.background.AudioService}
     app=ProcessRecord{6bd1649 2708:com.dev2qa.example/u0a85}
     createTime=-15s832ms startingBgTimeout=--
     lastActivity=-15s832ms restartTime=-15s832ms createdFromFg=true
     * IntentBindRecord{2411d72 CREATE}:

4. Android Background Service Example.

Below is this example project java files structure. You can see this example demo video at the end of this article.


4.1 Main Activity Java File.

package com.dev2qa.example.service;

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

import com.dev2qa.example.R;

public class CreateBackgroundServiceActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {

        setTitle(" - Android Background Service Example.");

        Button startBackService = (Button)findViewById(;
        startBackService.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                // Start android service.
                Intent startServiceIntent = new Intent(CreateBackgroundServiceActivity.this, MyBackgroundService.class);

        Button stopBackService = (Button)findViewById(;
        stopBackService.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                // Stop android service.
                Intent stopServiceIntent = new Intent(CreateBackgroundServiceActivity.this, MyBackgroundService.class);

4.2 Custom Android Background Service Java File.

package com.dev2qa.example.service;

import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyBackgroundService extends Service {

    public MyBackgroundService() {

    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");

    public void onCreate() {
        Toast.makeText(this, "Invoke background service onCreate method.", Toast.LENGTH_LONG).show();

    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Invoke background service onStartCommand method.", Toast.LENGTH_LONG).show();
        return super.onStartCommand(intent, flags, startId);

    public void onDestroy() {
        Toast.makeText(this, "Invoke background service onDestroy method.", Toast.LENGTH_LONG).show();

4.3 Layout Xml File.



        android:text="Start Background Service"

        android:text="Stop Background Service"


5. How To Make An Android Background Service Run Always.

  1. Return START_STICKY when you override the background service class’s onStartCommand method.
    public int onStartCommand(Intent intent, int flags, int startId) 
        Toast.makeText(this, "Invoke background service onStartCommand method.", Toast.LENGTH_LONG).show();
        return START_STICKY;
  2. Create a custom service binder class.
    # The class should extends the Binder class.
    public class MyBackgroundServiceBinder extends Binder {
            public MyBackgroundService getService() {
                    # Return the MyBackgroundService instance.
                    return MyBackgroundService.this;
  3. Create the background service connection object.
    private MyBackgroundServiceConnection m_serviceConnection = new MyBackgroundServiceConnection() {
            public void onServiceConnected(ComponentName className, IBinder service) {
                    m_service = ((MyBackgroundService.MyBackgroundBinder)service).getService();
            public void onServiceDisconnected(ComponentName className) {
                    m_service = null;
  4. Call bindService method to bind intent to the service.
    Intent intent = new Intent(this, MyBackgroundService.class);
    bindService(intent, m_serviceConnection, BIND_AUTO_CREATE);
  5. Send an android notification to make the android activity auto restart when it is closed.
    private void addNotification() {
            // Create a Notification.Builder object.
            Notification.Builder notificationBuilder = new Notification.Builder(this);
            // Set the service name as the notification title. 
            // Set the notification content from the resource file.      
            // Set the notification icon.      
            // create an intent object.
            Intent intent = new Intent(this, MyBackgroundService.class);
            // Convert the above intent object to a PendingIntent object.
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
            // Call the notificationBuilder's setContentIntent method to append the pending intent to it.
            // send the notification to android os.
  6. Modify the android project’s AndoridManifest.xml file to make the activity started in singleTop mode, which means it always runs at the top of the Android stack.
    <activity android:name=".service.background.CreateBackgroundServiceActivity" 
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
  7. The android os may kill your background service if it finds fewer resources and the background service is not active, then you may need to start it as a foreground service, you can read the article Android Foreground Service Example.

4 thoughts on “How To Create, Start, Stop Android Background Service”

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.