时间:2010-07-25 18:44:07

标签: android alarm

3 个答案:

答案 0 :(得分:79)

答案 1 :(得分:4)

我尝试了各种方法并且无法使它工作,所以我决定做一个肮脏的把戏。当我想取消重复闹钟时,我使用创建闹钟的相同方法(因此替换旧闹钟)然后立即取消它。使用此方法,如果布尔变量设置为true,则会创建一个它替换的警报,然后取消具有相同ID的替换:

static void CancelRepeatingAlarm(Context context, boolean creating){
    //if it already exists, then replace it with this one
    Intent alertIntent = new Intent(context, AlertReceiver.class);
    PendingIntent timerAlarmIntent = PendingIntent
            .getBroadcast(context, 100, alertIntent,PendingIntent.FLAG_CANCEL_CURRENT); 
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (creating){
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), INTERVAL, timerAlarmIntent);
    }else{
        alarmManager.cancel(timerAlarmIntent);
    }

答案 2 :(得分:3)

MainActivity中,设置闹钟时间。如果您要使用多个警报,请使用SharedPreferences存储各自的ID。这是代码:

PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, _id,intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(),
            pendingIntent);

public static Context getContext() {
    return mContext;
}
mContext=mainactivity.this;

在您的第二个Activity中使用来自SharedPreferences的相同ID。在我的代码中,我从ArrayList Alarm_id获取ID。最后,您可以在此处使用MainActivity上下文MainActivity.getContext()。这是代码:

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intentAlarm = new Intent(AlarmListviewActivity.this,
        MainActivity.class);
PendingIntent morningIntent = PendingIntent.getBroadcast(MainActivity.getContext(), Alarm_id.get(positon),
        intentAlarm, PendingIntent.FLAG_CANCEL_CURRENT);

alarmManager.cancel(morningIntent);
morningIntent.cancel();