java无法在Android中使用AlarmManager停止服务
我有一个alarm manager启动服务的代码。我必须用第二个闹钟在规定时间内取消它。我所看到的任何解决方案都不起作用。我的代码如下:
void startAtInterval(int fromTime, int fromTimeMinute, int toTime, int toTimeMinute, int id1, int id2) {
// start alarm
AlarmManager alarmMgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, fromTime);
calendar.set(Calendar.MINUTE, fromTimeMinute);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent);
// stop alarm
AlarmManager alarmMgr1 = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent1 = PendingIntent.getService(getApplicationContext(), 1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(System.currentTimeMillis());
calendar1.set(Calendar.HOUR_OF_DAY, toTime);
calendar1.set(Calendar.MINUTE, toTimeMinute);
alarmMgr1.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, alarmIntent1);
stopService(intent);
alarmMgr1.cancel(alarmIntent1);
}
我使用了FLAG_UPDATE_CURRENT
和FLAG_CANCEL_CURRENT
。我还试图stopservice
如我在代码中所示。我正在通过配置屏幕传递时间。我知道它是有效的,因为第一个警报总是被触发的
# 1 楼答案
要停止任何报警管理器,必须使用以下命令:
其中
NDX
与start相同。这就是0
在你的情况下。或者,更好的是,将NDX更改为某个随机常数要停止:
# 2 楼答案
你应该有第二个警报,取消服务,然后停止服务。这将确保警报在任何情况下都能成功停止服务,例如关闭应用程序
然后让你的
BroadcastReceiver
确保在舱单中声明接收人: