set Alarm using BroadcastReceiver - Android android.app

Android examples for android.app:Alarm Set up

Description

set Alarm using BroadcastReceiver

Demo Code

import java.util.HashSet;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.SystemClock;

public class Main {

  public static HashSet<PendingIntent> set = new HashSet<PendingIntent>();

  public static void setAlarm(Context ctx, BroadcastReceiver rcv, String action, int id, long time) {
    // Alarm Manager
    IntentFilter intentFilter = new IntentFilter(action);

    AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);

    ctx.registerReceiver(rcv, intentFilter);

    Intent alarm = new Intent(action);
    PendingIntent sender = PendingIntent.getBroadcast(ctx, id, alarm, PendingIntent.FLAG_UPDATE_CURRENT);

    long current = SystemClock.elapsedRealtime();
    am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, current + time, sender);
    set.add(sender);/* www.  j  ava  2 s.co  m*/
  }

}

Related Tutorials