我正在创建一个应用,用户可以根据GPS位置设置闹钟。我只想在任何时候激活1个警报。因此,当用户设置第二个警报时,我想取消第一个警报的通知(然后为第二个警报设置新的通知)。
现在,我的通知继续堆叠(因为我无法删除它们,因此它们都处于活动状态)。这是我的代码,我试图删除警报和通知:
// Stop the location alarm activity
Intent intentAlarmService_delete = new Intent(v.getContext(), AlarmService.class);
stopService(intentAlarmService_delete); // I think this calls onDestroy() in AlarmService class ...
mNtf = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNtf.cancelAll();
Intent alarmIntent2 = new Intent(getApplicationContext(), OneTimeAlarmReceiver.class);
PendingIntent pendingIntentAlarm = PendingIntent.getBroadcast(getApplicationContext(), PENDING_INTENT_REQUEST_CODE1,
alarmIntent2, PendingIntent.FLAG_CANCEL_CURRENT);
pendingIntentAlarm.cancel();
这是我的AlarmService.class中的onDestroy()函数(我不确定何时调用它...)
public void onDestroy(){
super.onDestroy();
mNtf.cancel(NOTIFICATION_ID1);
Intent alarmIntent = new Intent(getApplicationContext(), OneTimeAlarmReceiver.class);
PendingIntent pendingIntentAlarm = PendingIntent.getBroadcast(getApplicationContext(), PENDING_INTENT_REQUEST_CODE1,
alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
pendingIntentAlarm.cancel();
Intent intentAlarmService = new Intent(getApplicationContext(), AlarmService.class);
stopService(intentAlarmService);
mNtf.cancel(NOTIFICATION_ID1);
mNtf.cancelAll();
}
然后,这就是我设置新警报和通知的方式:
Intent intentAlarmService2 = new Intent(v.getContext(), AlarmService.class);
startService(intentAlarmService2);
顺便说一句,我的AlarmService.class肯定在运作。
提前致谢。
答案 0 :(得分:7)
首先,摆脱getApplicationContext()
。你几乎从不需要它,而且经常是错误的选择。将其替换为this
,因为您在上调用getApplicationContext()
的任何内容是Context
。
在您列出的代码中,您永远不会提出Notification
。因此,很难帮助你弄清楚为什么你会得到多个。在cancelAll()
上拨打NotificationManager
可以清除您应用中的所有未完成通知。
我最好的猜测是,onDestroy()
未在您的服务中调用。如果其他东西将服务保留在内存中(例如,您通过bindService()
与它建立了活动绑定连接),就会发生这种情况。或者,您可能在清单中的<service>
元素中有一些奇怪的东西(例如,一个不必要的android:process
属性),这会导致NotificationManager
cancel()
操作混乱。
答案 1 :(得分:2)
您需要确保始终引用NotificationManager的同一实例。不同的实例会产生不同的通知。我建议使用服务来管理通知。