8

How can I start a Service when the Android device is turned on and the OS is running?

homerman
  • 3,369
  • 1
  • 16
  • 32
Adham
  • 63,550
  • 98
  • 229
  • 344

1 Answers1

26

Add to AndroidManifest.xml:

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

<service android:name=".YourService" />

<receiver android:name="com.your.package.AutoStart">  
    <intent-filter>  
        <action android:name="android.intent.action.BOOT_COMPLETED" />  
    </intent-filter>  
</receiver>

Create class AutoStart.java:

public class AutoStart extends BroadcastReceiver
{

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

}
ciscogambo
  • 1,160
  • 11
  • 18
  • 2
    But does the BroadcastReceiver start receiving Broadcast as soon as the device complete booting, without the need to run the application? If yes, when does the broadcast receiver will be registered ? – Adham Oct 05 '11 at 23:49
  • 3
    Yes, the OS will call your AutoStart.onReceive() method when the device is booted. Note that this may be before the SD card is mounted. When you install the apk, the system will look at your manifest and your app will be registered with the system for you to start on boot. – ciscogambo Oct 05 '11 at 23:54