Wednesday, October 17, 2012

How to restart service with AlarmManager ?

Supposed you are running the below service......We just need to register and unregister the alarm,in service lifecycle.



package com.example.differentlayout;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

class PersistentService extends Service {

private static final String TAG = "PersistentService";

// support persistent of Service
void registerRestartAlarm() {
Log.d(TAG, "registerRestartAlarm");
Intent intent = new Intent(PersistentService.this, RestartService.class);
intent.setAction(RestartService.ACTION_RESTART_PERSISTENTSERVICE);
PendingIntent sender = PendingIntent.getBroadcast(PersistentService.this, 0, intent, 0);
long firstTime = SystemClock.elapsedRealtime();
firstTime += 10 * 1000; // 10 seconds after the alarm event occurs
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,10 * 1000, sender);
}

void unregisterRestartAlarm() {
Log.d(TAG, "unregisterRestartAlarm");
Intent intent = new Intent(PersistentService.this, RestartService.class);
intent.setAction(RestartService.ACTION_RESTART_PERSISTENTSERVICE);
PendingIntent sender = PendingIntent.getBroadcast(PersistentService.this, 0, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(sender);
}

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

@Override
public void onCreate() {
unregisterRestartAlarm();
super.onCreate();
}

@Override
public void onDestroy() {
registerRestartAlarm();
super.onDestroy();
}

}



Write the receiver which wake ups our above service....


package com.example.differentlayout;

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

public class RestartService extends BroadcastReceiver {
 public static final String ACTION_RESTART_PERSISTENTSERVICE = "ACTION.Restart.PersistentService";

@Override
 public void onReceive(Context context, Intent intent) {
   Log.d("RestartService", "RestartService called!@!@@@@@#$@$@#$@#$@#");
   if(intent.getAction().equals(ACTION_RESTART_PERSISTENTSERVICE)) {
     Intent i = new Intent(context, PersistentService.class);
     context.startService(i);
 }
}
}


In manifest file don't forgot to mention the RestartService as remote.....


<receiver android:name="RestartService" android:process=":remote">
       <intent-filter>
                       <action android:name="ACTION.Restart.PersistentService"></action>
        </intent-filter>
</receiver>


No comments:

Post a Comment