Wednesday, April 13, 2011

Auto start a service with Intent of "android.intent.action.BOOT_COMPLETED" action

Last exercise "Start a service to send Notification" show how to start a service by user clicking in a activity. In this exercise, a BroadcastReceiver will be implemented to receive Intent of "android.intent.action.BOOT_COMPLETED" action after power-up, no interactive with user.

"android.intent.action.BOOT_COMPLETED" is Broadcast Action, is broadcast once, after the system has finished booting. It can be used to perform application-specific initialization. You must hold the RECEIVE_BOOT_COMPLETED permission in order to receive this broadcast.

Create a new class, extends BroadcastReceiver. Simple do the same thing as that in Start button OnClickListener in last exercise "Start a service to send Notification", start a service.
package com.exercise.AndroidNotifyService;

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

public class AutoStartNotifyReceiver extends BroadcastReceiver {

private final String BOOT_COMPLETED_ACTION = "android.intent.action.BOOT_COMPLETED";

public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub

Intent myIntent = new Intent(context, com.exercise.AndroidNotifyService.NotifyService.class);



In order to receive Intent of "android.intent.action.BOOT_COMPLETED", modify AndroidManifest.xml to add <receiver> for AutoStartNotifyReceiver, also grant permission of "android.permission.RECEIVE_BOOT_COMPLETED".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AndroidNotifyService"
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<service android:name=".NotifyService"/>
<receiver android:name=".AutoStartNotifyReceiver" android:label="@string/app_name">
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.LAUNCHER" />

Keep using the other files implemented in last exercise "Start a service to send Notification".

Download the files.


yonaides said...

your post are excelent and i used to
ground in android world thanks so much.

Alex Semykin said...

If I have a Button "Stop Service" and push it, the service will stop, but it will start after boot anyway (and I don't want it).
How can I manage this?