How To Create, Start, Stop Android Background Service

Android service is a very important component in android app development. It is generally run in background. It do not has user interface. If you start it in activity then it is run in the activity main thread. So when the activity is destroyed, the background service started in it is destroyed also.

1. How To Create Background Service In Android Studio.

  1. Right click the package name in android studio.
  2. Click New —> Service —> Service menu.
    create android service component in android studio
  3. In next android component configuration panel, input service name, check all checkbox. Exported means other apps besides current app can invoke this service component, Enabled means this service component is ready to be used.
    create new background service configuraton panel
  4. Click Finish button, you will get a class that extends android.app.Service. And the service object is also configured in AndroidManifest.xml file as below.
    <service
        android:name=".service.MyBackgroundService"
        android:enabled="true"
        android:exported="true"></service>

2. Android Background Service Methods.

Below methods are most commonly overrided methods in android background service component.

  1. onCreate : This method is invoked only once when the background service component is created for the first time.
  2. onStartCommand : This method is invoked every time when the background service is started. You can execute task or start child thread in this method. Because android background service is executed in main activity thread, so if you do not use child thread and if the task is very time consuming, activity main thread will be blocked by the service object.
  3. onDestroy : When the background service is destroyed, this method will be called. You can release related resouces in it.
  4. stopSelf : This method can stop the running android background service by it self.
READ :   Android Keep Broadcast Receiver Running After Application Exit

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

  1. Start android background service.
    Intent intent = new Intent(Activity.this, MyBackgroundService.class);
    startService(intent);
  2. Stop android background service.
    Intent intent = new Intent(Activity.this, MyBackgroundService.class);
    stopService(intent);
  3. After you start the background service, you can go to Settings —> Developer options —> Running services to see it.
    andrlid list background service
  4. You can also execute below shell command to list all the running services.
    adb shell service list

4. Android Background Service Example.

how to create start stop android background service

Below is the java file structure for this example.

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>
(Visited 15 times, 2 visits today)

Leave a Reply

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