Android UI How to - Cancel alert with AlarmManager








Question

We would like to know how to cancel alert with AlarmManager.

Answer

//from   w ww .  j a va  2  s . c o m
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

class Alert {
  private Context mContext;
  private static final String ALERT_STR = "string";

  public Alert(Context context) {
    super();
    mContext = context;
  }

  public void alertAtTime(long triggerAtTime, int noteId) {
    Intent i = new Intent(mContext, Alert.class);
    i.setAction(ALERT_STR + noteId);
    PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, i, 0);
    AlarmManager alarmManager = (AlarmManager) mContext
        .getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtTime, 0,
        pendingIntent);
  }
  public void cancelAlert(int noteId) {
    AlarmManager alarmManager = (AlarmManager) mContext
        .getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(mContext, Alert.class);
    i.setAction(ALERT_STR + noteId);
    PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, i, 0);
    alarmManager.cancel(pendingIntent);
  }
}