Sunday, August 9, 2009

Android Development How-to: Launch an Activity on Phone Boot

This note is intended to get you going with the task in the subject in 5-10 minutes depending on your reading and typing speed. It applies to Android 1.5 (Cupcake).

Add this permission to AndroidManifest.xml:

<uses-permission name="android.permission.RECEIVE_BOOT_COMPLETED">

And a receiver element to the manifest:

<receiver name=".StartupBroadcastReceiver">
<intent-filter>
<action name="android.intent.action.BOOT_COMPLETED">
<category name="android.intent.category.HOME">
</intent-filter>
</receiver>

Create StartupBroadcastRecevier class similar to the following:

// replace with your package name
package com.burnayev.actioncomplete.android;

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

import com.burnayev.actioncomplete.android.activity.Main;

public class StartupBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Intent startupIntent = new Intent(context, Main.class); // substitute with your launcher class
startupIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startupIntent);
}

}

You are done.

To test that your application starts up on boot you have to:
  1. Run the application from Eclipse so that it gets installed on your phone.
  2. Reboot your device (turn it off then turn it on). When phone starts up you should see your application started after a delay.
Enjoy.

2 comments:

Exchange said...

hi...
but the activity doesn't start when the keypad is locked.

once i unlock, the activity is launched?

i need to start my activity on phone boot. this should be the first one.

any help?

Vineet said...

dude, its not working..there is a error in mainfest file...receiver..missing attribute name!!!! could you hlp me out?? I have tried every thing possible..please help me out