我正在使用targetSdkVersion 24.我设置了这样的警报:
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("REQUEST_CODE", CHEW_REQ_CODE);
intent.putExtra("CHEW_TEXT", chewText);
PendingIntent pIntent = PendingIntent.getBroadcast(context, CHEW_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, interval, pIntent);
其中间隔为15 x 60 x 1000 = 15 min。此警报在首选项的复选框中设置。在运行API 23的HTC One上,警报按预期启动。但是,当我通过取消选中首选项来取消此警报时,警报会一直停止。这是我的取消代码:
if (alarmMgr != null) {
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("REQUEST_CODE", CHEW_REQ_CODE);
intent.putExtra("CHEW_TEXT", chewText);
PendingIntent pIntent = PendingIntent.getBroadcast(context, CHEW_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmMgr.cancel(pIntent);
}
我错过了什么?
答案 0 :(得分:0)
您需要保留在alarmMgr.setRepeating(...)
中使用的原始PendingIntent对象,而不是创建新对象。这样的事情应该会有所帮助;
PendingIntent startAlarm(Context context){
AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("REQUEST_CODE", CHEW_REQ_CODE);
intent.putExtra("CHEW_TEXT", chewText);
PendingIntent pIntent = PendingIntent.getBroadcast(context, CHEW_REQ_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, interval, pIntent);
return pIntent;
}
void stopAlarm(Context context, PendingIntent pIntent) {
AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
if (alarmMgr!= null) {
alarmMgr.cancel(pIntent);
}
}
然后在你的班级中使用类似于以下内容(这里我使用onPause和onResume of Activity):
PendingIntent alarmIntent;
@Override
protected void onResume() {
super.onResume();
alarmIntent = startAlarm(this);
}
@Override
protected void onPause() {
super.onPause();
if (alarmIntent != null) {
stopAlarm(this, alarmIntent);
alarmIntent = null;
}
}
HTHS !!!
答案 1 :(得分:0)
感谢Blehi,我发现代码没有被调用。部分是这样的:
if (alarmMgr != null) {
alarmMgr.cancel(chewIntent);
}
AlarmReceived实现为Singleton,而AlarmManager在我的setAlarm中实例化。因此,当警报被取消时,alarmMgr为空。