Automatically starting Services in Android after booting

To start Services automatically after the Android system starts you can register a BroadcastReceiver to the Android android.intent.action.BOOT_COMPLETED system event.

In the onReceive() method the corresponding BroadcastReceiver would then start the service.

				
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		Intent service = new Intent(context, WordService.class);
		context.startService(service);
	}
}

If you application is installed on the SD card, then it is not available after the android.intent.action.BOOT_COMPLETED event. Register yourself in this case for the android.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE event.

Also note that as of Android 3.0 the user needs to have started the application at least once before your application can receive android.intent.action.BOOT_COMPLETED events.

You find more on Services in my Android Service and BroadcastReceiver Tutorial.

I hope this helps. You find me also on Twitter. My Google+ profile can be found Lars Vogels Profile.

About Lars Vogel

Lars Vogel is the founder and CEO of the vogella GmbH and works as Eclipse and Android consultant, trainer and book author. He is a regular speaker at international conferences, He is the primary author of vogella.com. With more than one million visitors per month this website is one of the central sources for Java, Eclipse and Android programming information.
This entry was posted in Android and tagged , , . Bookmark the permalink.

3 Responses to Automatically starting Services in Android after booting

  1. Moritz Post says:

    Once you receive the event you should not perform you work directly. It is better to schedule the work for a later time (like a couple of minutes) to not slow down the startup of the device.

  2. Thierry-Dimitri Roy says:

    Note that the BOOT_COMPLETED may not be called when the device is actually booted on Android 3.1+.

    See
    http://commonsware.com/blog/2011/07/05/boot-completed-regression.html

  3. Curly says:

    Actually, the ACTION_EXTERNAL_APPLICATIONS_AVAILABLE does not work for Applications on the SD card. See this StackOverflow question http://stackoverflow.com/questions/6391763/android-installlocation-and-boot-completed

Comments are closed.