Tuesday, December 23, 2014

Restart Android Service on Reboot of Phone

Recently in one of our project we have an android background service. Which we used to send some periodic updates to server. Later we identified an issue that the service was not restarted when phone restarts or switched off by low battery and power on again. In this blog I will explain you how to restart background service.

First of all you have to register a receiver for the device boot and power on action in your Android manifest file. This broadcast receiver will be invoked when this action happens. Following is the example code.

<receiver android:name=".BootCompletedIntentReceiver">
    <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
    <action android:name="android.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE" />


As you see above we have added BootCompletedIntentReceiver which is our broadcast receiver and added three actions.


BOOT_COMPLETED and QUICKBOOT_POWERON actions are invoked when phone powers on. ACTION_EXTERNAL_APPLICATIONS_AVAILABLE is required if your application is installed in external memory.

After that add following class to your project.

package com.mypackage.app;

import java.util.Calendar;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.mypackage.app.BackGroundService;

public class BootCompletedIntentReceiver extends BroadcastReceiver {

public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent serviceIntent = new Intent(context,
PendingIntent pintent = PendingIntent.getService(context, 0,
                                serviceIntent, 0);
                Calendar cal = Calendar.getInstance();
                int interval = 5;
                interval = interval * 60 * 1000;
                PendingIntent pintent = PendingIntent.getService(getBaseContext(), 0,
                               serviceIntent, 0);
                AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                               alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                                interval, pintent);

As you can see in above code. We have added BootCompletedIntentReceiver which extends broadcast receiver. onReceive event is called when there is an action and in that event we are creating pending and service intent for our background service and set alarm to invoke service at regular interval. 

Hope this posts help you.

No comments:

Post a Comment