How To Start Android Service Automatically At Boot Time

To start an android background service when the device boots, you should create a broadcast receiver, and make it listen to 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 methods to start an android service in the above onReceive method.

  1. Start the android service directly use intent. This is not a good choice because the background service is always run, and it needs to use thread to make the execution continue. This will cost resources and create errors.
  2. Start a repeat alarm, and make the alarm call the background service when executing every interval time. This is a good choice because the alarm is an 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 on an android device. The below picture is the android example app execution screen. There are 4 buttons on the app’s main screen. Each button will implement a different method to start the android service when the android device boots.
    run-any-activity-in-android-project-to-install-boot-completed-receiver
  2. Go to the Android Virtual Device Manager window, click the green button at the end of the device line to shut down the android device, and restart it again, then you can see the Toast message ( such as “BootDeviceReceiver onReceive, action is android.intent.action.BOOT_COMPLETED”, “Start service use repeat alarm.”  and “RunAfterBootService onStartCommand() method.”) and debug log in android monitor log cat console.
    launch-avd-in-avd-list
  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>

4. Question & Answer.

4.1 How to launch an android activity from a foreground service when the android device boots up.

  1. My requirement is to start a foreground service when the android device boots up, and at the same time, the foreground service will start an activity. I found this article from google but I find it can not implement my needs. How can I implement my needs?
  2. From android API version 29, you are not allowed to start an android activity from the background service, although you want to start the android activity from the foreground service, but android treats foreground service as a background process also, so when your android version is bigger than android 10, this action will be restricted. If you test your android app for a hard android device, and for some hard android devices, they may not allow you to start the application when the android device boots up, so If you want, you need some exclusive autostart permission on those android hard devices.

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
0 0 vote
Article Rating
Subscribe
Notify of
guest

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

5 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Claudio
Claudio

I miss something.. after:
insert the 2 classes , modify Manifest.xml,
starti the app (mainactivity of a new empty activity project),
shutdown emulator, restart emulator from AVD manager.. nothing
happens. Do i have to put some code in mainactivity to start the service?
I’m a pretty new android dummy..
Thank you for help
Claudio

Bahaa
Bahaa

good tutorial

Claudio
Claudio
Reply to  Bahaa

I miss something.. code to insert in mainactivity to start/register? Which one?
Thank you for help
a pretty dummy android developer…
Claudio

Someone Somewhere
Someone Somewhere

this information seems to conflict with the information presented at https://medium.com/@berriz_/service-and-boot-completed-on-android-o-6a389eae50f1

“Starting from Android O, you can not start a service from a background app without being blessed with an exception…”

vincent xian
vincent xian

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

5
0
Would love your thoughts, please comment.x
()
x