2012-08-13 60 views
7

我正在創建一個顯示當前播放歌曲notification的應用程序。如何取消意外/強制終止應用程序的通知

該歌曲正在播放通過Service &啓動&取消通知是在服務本身完成的。

但是,如果應用程序被某種異常終止,或者如果我強制通過任務管理器關閉它,通知將保留在任務欄的頂部。

我該如何刪除它。

下面是代碼:

//In Service onStartCommand(), there is a call to initiatePlayback() 
private void initiatePlayback() { 
    try { 
     if (mPlayer.isPlaying()) { 
      mPlayer.stop(); 
     } 
     mPlayer.reset(); 
     mPlayer.setDataSource(currentData); 
     mPlayer.prepare(); 

     if (reqAudioFocus()) { 
      mPlayer.start(); 
     } 

     if (mPlayer.isPlaying()) { 
      initNotification(); 
     } 
    } catch (Exception e) { 
     Toast.makeText(this, 
       "PlayTrack->initiatePlayback(): " + e.toString(), 
       Toast.LENGTH_SHORT).show(); 
    } 
} 

@Override 
public void onDestroy() { 
    stopPlayback(); 
    mPlayer.release(); 
    mPlayer = null; 
    super.onDestroy(); 
} 

private void stopPlayback() { 
    if (mPlayer.isPlaying()) { 
     mPlayer.stop(); 
     mPlayer.reset(); 
     cancelNotification(); 
    } 
} 
private void cancelNotification() { 
     String ns = Context.NOTIFICATION_SERVICE; 
     NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); 
     mNotificationManager.cancel(NOTIFICATION_ID); 
    } 
+2

檢查此: http://stackoverflow.com/questions/12997800/cancel-notification-on-remove-application-from-multitask-panel – 2014-03-13 23:51:03

回答

0

您可以覆蓋onDestroy()方法和使用NotificationManager取消通知。您只需提供應取消通知的ID。

@Override 
public void onDestroy() { 

    private static final int MY_NOTIFICATION_ID= 1234; 
    String ns = Context.NOTIFICATION_SERVICE; 
    NotificationManager mNotificationManager; 
    mNotificationManager = (NotificationManager) getSystemService(ns); 
    mNotificationManager.notify(MY_NOTIFICATION_ID, notification); 
    //to cancel: 
    mNotificationManager.cancel(MY_NOTIFICATION_ID); 
} 
+0

對不起..未加載整個相關代碼..做這個only..code added – reiley 2012-08-13 08:05:47

+0

@ raul8我的解決方案建議仍然適用於您的案例,因爲您的應用程序在終止時會進入onDestroy狀態,您可以簡單地使用我共享的代碼示例取消通知。你嘗試過嗎? – 2012-08-13 08:14:43

+3

是的..問題是OnDestroy甚至沒有被調用。我正在使用'System'任務管理器。事情是其他球員甚至沒有關閉,我認爲這是一個正確的功能。所以現在我會盡量不要通過任務管理器強制關閉播放。 – reiley 2012-08-13 10:45:50

1

捕獲異常和catch子句中取消:

mNotificationManager.cancel(MY_NOTIFICATION_ID); 
1

我知道這個問題是舊的,但我發現它時,我認爲是有類似的問題。對我來說,服務與應用程序一起被殺害(它正確地取消了onDestroy中的通知),但隨後被重新啓動(與START_STICKY一樣),並且通知再次被髮布。在這些情況下,我不想讓服務回來,直到用戶從應用程序啓動它,所以在OnStartCommand中,當傳入的意圖爲空時,我調用stopSelf()。

0

你能趕上與打破你的應用程序中的錯誤:

Thread.setDefaultUncaughtExceptionHandler(newHandler); 

注意,這樣做將無法申請到異常後關閉,所以你需要得到的是舊exceptionHandler的參考和從你叫它。

此外,添加代碼以刪除此方法的通知。