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.
    create-android-service-component-in-android-studio
  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.
    create-new-background-service-configuraton-panel
  4. When you click the Finish button in the above window, it will create the android background service class that extends android.app.Service. It will also add the service object configuration XML data in AndroidManifest.xml file as below.
    <service
        android:name=".service.MyBackgroundService"
        android:enabled="true"
        android:exported="true"></service>

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.
    startService(intent);
  2. Call stopSerivce(intent) method to stop the service.
    Intent intent = new Intent(Activity.this, MyBackgroundService.class);
    stopService(intent);
  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.
    android-list-background-service
  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}
     intent={cmp=com.dev2qa.example/.audio.background.AudioService}
     packageName=com.dev2qa.example
     processName=com.dev2qa.example
     baseDir=/data/app/com.dev2qa.example-1/base.apk
     dataDir=/data/user/0/com.dev2qa.example
     app=ProcessRecord{6bd1649 2708:com.dev2qa.example/u0a85}
     createTime=-15s832ms startingBgTimeout=--
     lastActivity=-15s832ms restartTime=-15s832ms createdFromFg=true
     Bindings:
     * IntentBindRecord{2411d72 CREATE}:
     intent={cmp=com.dev2qa.example/.audio.background.AudioService}

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.

android-background-service-project-file-structure

4.1 Main Activity Java File.

CreateBackgroundServiceActivity.java

package com.dev2qa.example.service;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.dev2qa.example.R;

public class CreateBackgroundServiceActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_background_service);

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

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


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

4.2 Custom Android Background Service Java File.

MyBackgroundService.java

package com.dev2qa.example.service;

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

public class MyBackgroundService extends Service {

    public MyBackgroundService() {
    }

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

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


    @Override
    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);
    }

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

4.3 Layout Xml File.

activity_create_background_service.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <Button
        android:id="@+id/start_background_service_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:text="Start Background Service"
        android:textAllCaps="false"/>

    <Button
        android:id="@+id/stop_background_service_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:text="Stop Background Service"
        android:textAllCaps="false"/>

</LinearLayout>

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. 
            notificationBuilder.setContentTitle(getText(R.string.service_name))
              
            // Set the notification content from the resource file.      
            notificationBuilder.setContentText(getResources().getText(R.string.service_status_monitor))
              
            // Set the notification icon.      
            notificationBuilder.setSmallIcon(R.drawable.notification_small_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.
            notificationBuilder.setContentIntent(pendingIntent);
    
            // send the notification to android os.
            notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
    }
  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" 
              android:launchMode="singleTop">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
    
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
  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.