如何取消Android通知?

Yas*_*ang 5 android

我正在创建一个应用程序,用户可以根据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();
Run Code Online (Sandbox Code Playgroud)

这是我的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();
}
Run Code Online (Sandbox Code Playgroud)

然后,这就是我设置新警报和通知的方式:

Intent intentAlarmService2 = new Intent(v.getContext(), AlarmService.class);
startService(intentAlarmService2);
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我的AlarmService.class肯定是有效的.

提前致谢.

Com*_*are 7

首先,摆脱getApplicationContext().你几乎从不需要它,而且经常是错误的选择.替换它this,因为你要求getApplicationContext()一个Context.

在您列出的代码中,您永远不会提出Notification.因此,很难帮助你弄清楚为什么你会得到多个.调用cancelAll()NotificationManager应该摆脱从您的应用程序的所有优秀通知.

我最好的猜测是,onDestroy()您的服务没有被调用.如果其他东西将服务保留在内存中(例如,您通过它有一个活动的绑定连接bindService()),就会发生这种情况.或者,您可能<service>在清单中的元素中有一些奇怪的东西(例如,一个不必要的android:process属性),这会对NotificationManager cancel()操作造成污染.