Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Starting a Service After Device Reboot

Author: Ashwini Shahapurkar
Published? true -- FormatLanguage: W

Problem:

You have a service in your app and you want it to start after the phone reboots.

Solution:

You need to listen to intent for boot events and start the service when event occurs.

Discussion:

Whenever the platform boot is completed, an intent with android.intent.action.BOOT_COMPLETED action is broadcasted. You need to register your application to receive this intent. For registering add this to your AndroidManifest.xml

<receiver android:name=".ServiceManager">
			<intent-filter>
				<action android:name="android.intent.action.BOOT_COMPLETED" />
			</intent-filter>
</receiver>

So you will have ServiceManager as broadcast receiver to receive the intent for boot event. The ServiceManager class shall be as follows:

public class ServiceManager extends BroadcastReceiver {

	Context mContext;
	private final String BOOT_ACTION = "android.intent.action.BOOT_COMPLETED";
	
	@Override
	public void onReceive(Context context, Intent intent) {
                // All registered broadcasts are received by this
		mContext = context;
		String action = intent.getAction();
		if (action.equalsIgnoreCase(BOOT_ACTION)) {
                        //check for boot complete event & start your service
			startService();
		} 
		
	}

	
	private void startService() {
                //here, you will start your service
		Intent mServiceIntent = new Intent();
		mServiceIntent.setAction("com.bootservice.test.DataService");
		mContext.startService(mServiceIntent);
	}
}

Since we are starting the Service, it too must be mentioned in AndroidManifest:

<service android:name=".LocationService">
    <intent-filter>
        <action android:name="com.bootservice.test.DataService"/>
    </intent-filter>
</service>

The Service class must of course extend Service; for more on this see the recipe Keeping a Service running while other apps are on display.

Both the XML receiver and service definitions must be inside the application element in AndroidManifest.xml. There is no requirement to have any Activity in this application at all, but it will probably be more user-friendly if you do. In one example we have used a PreferenceActivity implementation as the main (and only) Activity of an app whose service is started at Reboot.

No records found.