如何在Android中取消AlarmManager

时间:2012-06-15 17:04:22

标签: android alarmmanager android-pendingintent

我有一个警报,直到特定的小时和分钟才会响起。但是,一旦这个时间到来,每次我再次启动应用程序时它都会消失。 (当应用程序启动时,它会重置并检查是否有新警报。)

例如,它将在上午9:48结束。 9:48之前没有按预期发生任何事情。但是在9:48之后,每次应用程序启动时它都会继续运行(警报是一个简单的状态栏通知)。

这是代码 - 我哪里出错?

//此处设置闹钟 - 每次应用启动时都会调用此代码

public void setAlarm() {
 for (int i : AlarmDays) {

        Calendar cal = Calendar.getInstance();
        if (cal.get(Calendar.DAY_OF_MONTH) > i)
            cal.add(Calendar.MONTH, 1);
        cal.set(Calendar.DAY_OF_MONTH, i);
        cal.set(Calendar.HOUR, 9);
        cal.set(Calendar.MINUTE, 53);
        cal.set(Calendar.SECOND, 1);


        String Name = AlarmNames.get(count);
        count = 0 + 1;

        Intent intent = new Intent(ManageDebts.this, TimeAlarm.class);
        Bundle b = new Bundle();
        b.putString("keyvalue", Name);
        intent.putExtras(b);


        pendingIntent = PendingIntent.getBroadcast(this, i,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                pendingIntent);

    }
 }

TimeAlarm.class

public class TimeAlarm extends BroadcastReceiver {

NotificationManager nm;

@Override
public void onReceive(Context context, Intent intent) {

    String DebtName = intent.getStringExtra("keyvalue");

    nm = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    CharSequence from = "Payment Due: " + DebtName;
    CharSequence message = "Update your Balance Now";
    Intent notificationIntent = new Intent(context, ManageDebts.class);
    notificationIntent.getExtras();
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
            notificationIntent, 0);
    Notification notif = new Notification(R.drawable.icon, "Pay "
            + DebtName + " today!", System.currentTimeMillis());
    notif.setLatestEventInfo(context, from, message, contentIntent);
    notif.defaults = Notification.DEFAULT_SOUND
            | Notification.DEFAULT_LIGHTS;
    notif.flags = Notification.FLAG_SHOW_LIGHTS;
    notif.ledOnMS = 100;
    notif.ledOffMS = 100;
    notif.flags |= Notification.FLAG_AUTO_CANCEL;
    nm.notify(1, notif);
}

}

1 个答案:

答案 0 :(得分:1)

  

我在哪里设置它以忽略那些不在那一分钟,一小时和二分钟内的任何警报?之前或之后?

使用setAlarm()方法。在您进入循环之前从AlarmDays过滤掉内容,或者将cal.getTimeInMillis()System.currentTimeMillis()进行比较以查看它是否过去,或类似的内容。