2010-08-11 174 views
3

我正在制作一个应用程序,用户可以根据GPS位置设置闹钟。我只希望在任何时候都有1个闹钟处于活动状态。因此,当用户设置第二个闹钟时,我想要取消第一个闹钟的通知(然后设置第二个闹钟的新通知)。如何取消Android通知?

现在,我的通知继续堆叠(因为我无法删除它们,所以它们都是活动的)。这里是我的代码,我正在试图删除警报和通知(S):

// 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工作是肯定的。

在此先感谢。

回答

7

首先,摆脱getApplicationContext()。你几乎从不需要它,而且往往是错误的选择。将其替换为this,因为无论您在上致电的getApplicationContext() a Context

在您列出的代码中,您永远不会提出Notification。因此,很难帮助你弄清楚你为什么得到不止一个。在NotificationManager上调用cancelAll()应该清除应用程序中的所有未完成通知。

我最好的猜测是onDestroy()没有被您的服务调用。如果有其他内容将服务保留在内存中(例如,您通过bindService()与它建立了活动绑定连接),则会发生这种情况。或者,您的清单中的<service>元素可能有些奇怪(例如,不必要的android:process属性),可能会损坏NotificationManager 操作。

+0

嗯,我检查了你所建议的所有东西,但没有一个能够正常工作... (我不能使用“this”,因为我似乎得到一个错误 - 这可能导致所有代码都在“public void onClick(View v)“功能。)+(我不使用onBind();)+(在没有陌生的东西) – 2010-08-13 00:21:58

+0

我要说明到底发生了什么: 我尝试在NotificationManager调用cancelAll(),但: 1 )我设置了一个新的通知(它显示在“通知窗口” - 当你从屏幕顶部向下滑动手指到底部时) 2)我删除了通知(它从“通知窗口” 3消失)我设置了一个新的通知***(它显示在“通知窗口”中,但是之前的通知(已被删除)显示在最新的通知(刚刚设置)之上),并且2个通知保持闪烁/交替“通知窗口” – 2010-08-13 00:22:17

+0

@亚西尔玛朗:“我不能使用”这个“,因为我似乎得到一个错误” - 你是在内部类中,然后需要使用'MyOuterClass.this'(将您的活动类名称替换为'MyOuterClass')。 – CommonsWare 2010-08-13 00:27:34

2

您需要确保始终引用NotificationManager的同一个实例。不同的实例会产生不同的通知。我建议使用服务来管理通知。

http://developer.android.com/guide/topics/fundamentals.html

+7

'NotificationManager'只是在另一个进程中运行的系统服务的代理。我有一个示例项目(http://github.com/commonsguy/cw-android/tree/master/Notifications/Notify1/),它不符合您的描述。如果您有证据表明“NotificationManager”按照您的描述工作,请将其指向我! – CommonsWare 2010-08-11 19:02:46

+0

使用不同的NotificationManager实例不会生成不同的通知。这一切都取决于你的通知ID。 – 2014-05-13 16:36:26