Automatically starting an Android application service on boot

If you (auto)start a background service it won’t be visible to the user. Users might think that the application is still active after they reboot the phone, but actually NO . Keep this in mind when using a service.

First of all we need to make sure your application is allowed to receive and handle the broadcast that tells the application that your phone was booted.

To be able to receive the broadcast you should add this permission as a child of the <manifest> element to your Android Manifest:


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

So, right now our application has the permission to receive a broadcasted message to tell us the phone was booted. In order to do anything with this broadcast we need to have a BroadcastReceiver. An example would look like this:


package com.example.application;

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

public class ItudeMobileBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()))
{
/* Only perform this below code if the BroadcastReceiver received the ACTION_BOOT_COMPLETED action.*/
Log.d("BroadcastReceiver","BroadcastReceiver ....run .......");
}
}

}

An important thing to know is that the onReceive method will be called whenever the class is declared in your manifest and wishes to receive the specified Intent. Let’s let our application know that our BroadcastReceiver exists and wishes to receive the android.intent.action.BOOT_COMPLETED intent. Add this to your <application> element of your Android Manifest:


<receiver android:enabled=”true” android:name=”com.itude.mobile.broadcast.ItudeMobileBroadcastReceiver” android:permission=”android.permission.RECEIVE_BOOT_COMPLETED”>

<intent-filter>

<action android:name=”android.intent.action.BOOT_COMPLETED” />

</intent-filter>

</receiver>

Advertisements