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 AutoStartNotifyReceiver.java, 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="http://schemas.android.com/apk/res/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.


Thank you for reading this article Auto start a service with Intent of "android.intent.action.BOOT_COMPLETED" action With URL http://x-tutorials.blogspot.com/2011/04/auto-start-service-with-intent-of.html. Also a time to read the other articles.


Write your comment for this article Auto start a service with Intent of "android.intent.action.BOOT_COMPLETED" action above!