我正在尝试停止警报并检查警报是否停止,但它始终返回true表示警报正在运行。我试图根据链接https://stackoverflow.com/a/17616299/1226882中的答案停止闹钟,但它对我不起作用。
请参阅以下代码
启动闹钟
public static void startSchedulerAlaram(Context ctx) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
if (calendar.compareTo(Calendar.getInstance()) <= 0)
calendar.add(Calendar.DATE, 1);
AlarmManager alarmManager = (AlarmManager) ctx
.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(ctx, Alaram_Receiver.class);
intent.setAction(Utility.SCHEDULE_ACTION);
PendingIntent pi = PendingIntent.getBroadcast(ctx, 1, intent,0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pi);
log("Scheduler Alarm", "Started");
}
停止闹钟
public static void stopSchedulerAlaram(Context ctx) {
Intent intent = new Intent(ctx, Alaram_Receiver.class);
intent.setAction(Utility.SCHEDULE_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, 1,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) ctx
.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
log("Scheduler Alarm", "Stopped");
}
检查闹钟
public static boolean checkSchedulerAlaram(Context ctx) {
boolean alarmUp = (PendingIntent.getBroadcast(ctx, 1, new Intent(ctx,Alaram_Receiver.class).setAction(Utility.SCHEDULE_ACTION),
PendingIntent.FLAG_NO_CREATE) != null);
return alarmUp;
}
答案 0 :(得分:1)
您必须通过different id for set alarm
PendingIntent.getBroadcast(ctx, id, intent,PendingIntent.FLAG_UPDATE_CURRENT);
cancel alarm you have pass same
id that you used for set
。
PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, id,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) ctx
.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
答案 1 :(得分:1)
您正在使用此代码确定警报是否已设置:
boolean alarmUp = (PendingIntent.getBroadcast(ctx, 1, new Intent(ctx,Alaram_Receiver.class).setAction(Utility.SCHEDULE_ACTION),
PendingIntent.FLAG_NO_CREATE) != null);
此代码依赖PendingIntent
的存在来确定警报是否已安排。
取消闹钟时,请执行以下操作:
PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, 1,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) ctx
.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
这会取消闹钟,但不会从系统中删除PendingIntent
。由于您依赖于PendingIntent
的存在/不存在来知道警报是否已经安排,您还需要取消PendingIntent
以便将其从系统中删除。这样做(取消警报后):
pendingIntent.cancel();
答案 2 :(得分:0)
这是我用来取消闹钟服务的代码
Intent intent = new Intent(this, MyReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);