How To Start Android Service Automatically At Boot Time

To start an android background service when device boot, you should create a broadcast receiver, and make it listen android.intent.action.BOOT_COMPLETED¬†action. Then in the custom broadcast receiver’s onReceive method, you can start the background service.

1. Method To Start Android Service When Device Boot Completed.

There are two method to start service in above onReceive method.

  1. Start the service directly use intent. This is not the good choice because the background service is always run, and it need to use thread to make the execution continue. This will cost resource and create errors.
  2. Start a repeat alarm, and make the alarm call the background service when execute every interval time. This is a good choice because the alarm is android OS system level service, it is controlled by android OS. It is run out of any application. And the background service will only execute when the alarm execute.

2. Start Android Service When Boot Completed Example.

  1. Start any activity in your android project to install BOOT_COMPLETED receiver in android device.
    run any activity in android project to install boot completed receiver
  2. Shutdown the android device and restart it again in android virtual device manager, then you can see Toast message and debug log in android monitor log cat console.
    launch avd in avd list
    use alarm to start android service automatically at boot time
  3. You can also see the debug log output in android monitor log cat console.
    use alarm to start android service automatically at boot time debug log

3. Auto Start Service After Device Boot Source Code.

auto start service after android device boot file structure

3.1 BOOT_COMPLETED Action Receiver.

BootDeviceReceiver.java

package com.dev2qa.example.alarm.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class BootDeviceReceiver extends BroadcastReceiver {

    private static final String TAG_BOOT_BROADCAST_RECEIVER = "BOOT_BROADCAST_RECEIVER";

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();

        String message = "BootDeviceReceiver onReceive, action is " + action;

        Toast.makeText(context, message, Toast.LENGTH_LONG).show();

        Log.d(TAG_BOOT_BROADCAST_RECEIVER, action);

        if(Intent.ACTION_BOOT_COMPLETED.equals(action))
        {
            //startServiceDirectly(context);

            startServiceByAlarm(context);
        }
    }

    /* Start RunAfterBootService service directly and invoke the service every 10 seconds. */
    private void startServiceDirectly(Context context)
    {
        try {
            while (true) {
                String message = "BootDeviceReceiver onReceive start service directly.";

                Toast.makeText(context, message, Toast.LENGTH_LONG).show();

                Log.d(TAG_BOOT_BROADCAST_RECEIVER, message);

                // This intent is used to start background service. The same service will be invoked for each invoke in the loop.
                Intent startServiceIntent = new Intent(context, RunAfterBootService.class);
                context.startService(startServiceIntent);

                // Current thread will sleep one second.
                Thread.sleep(10000);
            }
        }catch(InterruptedException ex)
        {
            Log.e(TAG_BOOT_BROADCAST_RECEIVER, ex.getMessage(), ex);
        }
    }

    /* Create an repeat Alarm that will invoke the background service for each execution time.
     * The interval time can be specified by your self.  */
    private void startServiceByAlarm(Context context)
    {
        // Get alarm manager.
        AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

        // Create intent to invoke the background service.
        Intent intent = new Intent(context, RunAfterBootService.class);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        long startTime = System.currentTimeMillis();
        long intervalTime = 60*1000;

        String message = "Start service use repeat alarm. ";

        Toast.makeText(context, message, Toast.LENGTH_LONG).show();

        Log.d(TAG_BOOT_BROADCAST_RECEIVER, message);

        // Create repeat alarm.
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startTime, intervalTime, pendingIntent);
    }
}

3.2 Background Service.

RunAfterBootService.java

package com.dev2qa.example.alarm.service;

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

public class RunAfterBootService extends Service {

    private static final String TAG_BOOT_EXECUTE_SERVICE = "BOOT_BROADCAST_SERVICE";

    public RunAfterBootService() {
    }

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

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG_BOOT_EXECUTE_SERVICE, "RunAfterBootService onCreate() method.");

    }

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

        String message = "RunAfterBootService onStartCommand() method.";

        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();

        Log.d(TAG_BOOT_EXECUTE_SERVICE, "RunAfterBootService onStartCommand() method.");

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

3.3 Android Manifest Xml File.

AndroidManifest.xml

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

    <!-- Example need below permission. -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <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/AppTheme">
        
        <receiver
            android:name=".alarm.service.BootDeviceReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>


        <service
            android:name=".alarm.service.RunAfterBootService"
            android:enabled="true"
            android:exported="true"></service>
    </application>

</manifest>

Reference

  1. Android Broadcast Overview
  2. How To Register Android BroadcastReceiver Statically
  3. How To Create, Start, Stop Android Background Service
  4. Android One Time / Repeat Alarm Example
(Visited 12,188 times, 5 visits today)
READ :   Android ImageView Matrix Rotate, Scale, Skew, Translate Example

2 Comments


  1. Hi there,

    You still need to register the Broadcast receiver in the MainActivity right? I wan to create an application that starts the service after boot up sequences are finished, but I do not want to show the UI–just like the service run in the background silently.

    Thank you

    Reply

Leave a Reply

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.