2010-08-11 66 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