Thursday, 13 June 2013

Alarm Management


To start some process continuously with some time interval we need the AlarmManager class to achieve the task

To start Alarm service by
AlarmService.start(Context context,long interval_day);
 To stop that Alarm Service by
AlarmService.stop(Context context);
To Restart the Alarm Service by
AlarmService.restart(Context context,long interval_day);

1.AlarmService.java
public class AlarmService {

 static Intent intent;
 static PendingIntent pendingIntent;
 static AlarmManager alarmManager;

 @SuppressWarnings("static-access")
 static void init(Context con) {
  intent = new Intent(con, MyAlarmBroadcastReceiver.class);
  pendingIntent = PendingIntent.getBroadcast(con.getApplicationContext(),
    234324243, intent, 0);
  alarmManager = (AlarmManager) con.getSystemService(con.ALARM_SERVICE);
 }

 public static void start(Context con, long day) {
  init(con);
  Calendar c = Calendar.getInstance();
  long seconds = day * 24 * 60 * 60 * 1000;
  alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),
    seconds, pendingIntent);
  Log.e("Alarm is started", " ok ");
 }

 public static void stop(Context con) {
  init(con);
  alarmManager.cancel(pendingIntent);
  Log.e("Alarm is  ", " stopped ");
 }

 public static void restart(Context con, long day) {
  stop(con);
  start(con, day);
 }
}

2. MyAlarmBroadcastReceiver.java

public class MyAlarmBroadcastReceiver extends BroadcastReceiver  {
 @Override
 public void onReceive(Context context, Intent intent) {
  Log.e("Alarm is ", "start");
  // Do Some Action for the Alarm is started 
 }
}





No comments:

Post a Comment

Disqus for Android