Trying to start a service on boot on Android

Alex picture Alex · May 6, 2010 · Viewed 190k times · Source

I've been trying to start a service when a device boots up on android, but I cannot get it to work. I've looked at a number of links online but none of the code works. Am I forgetting something?

AndroidManifest.xml

<receiver
    android:name=".StartServiceAtBootReceiver"
    android:enabled="true"
    android:exported="false"
    android:label="StartServiceAtBootReceiver" >
    <intent-filter>
        <action android:name="android.intent.action._BOOT_COMPLETED" />
    </intent-filter>
</receiver>

<service
    android:name="com.test.RunService"
    android:enabled="true" />

BroadcastReceiver

public void onReceive(Context context, Intent intent) {
    if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
        Intent serviceLauncher = new Intent(context, RunService.class);
        context.startService(serviceLauncher);
        Log.v("TEST", "Service loaded at start");
    }
}

Answer

Timo Bruck picture Timo Bruck · Mar 26, 2011

The other answers look good, but I thought I'd wrap everything up into one complete answer.

You need the following in your AndroidManifest.xml file:

  1. In your <manifest> element:

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    
  2. In your <application> element (be sure to use a fully-qualified [or relative] class name for your BroadcastReceiver):

    <receiver android:name="com.example.MyBroadcastReceiver">  
        <intent-filter>  
            <action android:name="android.intent.action.BOOT_COMPLETED" />  
        </intent-filter>  
    </receiver>
    

    (you don't need the android:enabled, exported, etc., attributes: the Android defaults are correct)

    In MyBroadcastReceiver.java:

    package com.example;
    
    public class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Intent startServiceIntent = new Intent(context, MyService.class);
            context.startService(startServiceIntent);
        }
    }
    

From the original question:

  • it's not clear if the <receiver> element was in the <application> element
  • it's not clear if the correct fully-qualified (or relative) class name for the BroadcastReceiver was specified
  • there was a typo in the <intent-filter>