我创造了一个每分钟都会响起的重复闹钟。我创建了一个具有2个静态函数的类来启动和取消警报。我这样做了所以我可以从多个地方开始并取消它。启动警报工作正常,但取消则没有。我在调用startAlarm
和cancelAlarm
时使用的上下文是getApplicationContext()
。我认为这可能是上下文的问题,但我不确定。有什么想法吗?
这是我的班级
public class Alarm {
public static PendingIntent pendingIntent;
public static AlarmManager manager;
public static Intent alarmIntent;
public static void startAlarm(Context context) {
Log.e("ALARM", "------------STARTED----------------");
alarmIntent = new Intent((context), AlarmReceiver.class);
alarmIntent.setAction("NOTIFICATION_ALARM");
pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
int alarmType = AlarmManager.RTC_WAKEUP;
Calendar cal = Calendar.getInstance();
long intervalTime = 1 * 60 * 1000;
manager.setRepeating(alarmType, cal.getTimeInMillis(), intervalTime, pendingIntent);
}
public static void cancelAlarm(Context context) {
alarmIntent = new Intent(context, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (manager != null) {
Log.e("ALARM", "------------STOPPED----------------");
manager.cancel(pendingIntent);
}
}
}
答案 0 :(得分:0)
使用cancel()
上的AlarmManager
及其PendingIntent
与您在setRepeating()中使用的Intent intent = new Intent(this, AlarmReceive.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
:
Date
答案 1 :(得分:0)
您取消的Intent
上的PendingIntent
需要与您用于设置闹钟的alarmIntent.setAction("NOTIFICATION_ALARM");
匹配,如Intent#filterEquals(Intent)
方法所定义。也就是说,您还需要在cancelAlarm()
方法中调用luaState.getGlobal(function);
luaState.pushJavaObject(obj);
luaState.call(1, 1);
。