Automatically starting Services from a Receivers

A common requirement is to automatically start a service after a system reboot, i.e., for synchronizing data. For this you can register a receiver for the android.intent.action.BOOT_COMPLETED system event. This requires the android.permission.RECEIVE_BOOT_COMPLETED permission.

The following example demonstrates the registration for the BOOT_COMPLETED event in the Android manifest file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.vogella.android.ownservice.local"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

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

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name=".ServiceConsumerActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="MyScheduleReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <receiver android:name="MyStartServiceReceiver" >
        </receiver>
    </application>

</manifest>
 
The receive would start the service as demonstrated in the following example code.
 
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) {
                // assumes WordService is a registered service
                Intent intent = new Intent(context, WordService.class);
                context.startService(intent);
        }
}

Note:
1) If your application is installed on the SD card, then it is not available after the android.intent.action.BOOT_COMPLETED event. In this case register it for the `android.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE ` event. 

2) Remember that as of Android API level 11 the user needs to have started the application at least once before your application can receive android.intent.action.BOOT_COMPLETED events.


No comments:

Post a Comment