How to cancel notification of unexpected / forced application termination

I am creating an application that displays a notification current executable song.

The song is played through the Service , and the initiation and cancellation of the notification is performed in the service itself.

But if the application is terminated by any exception or I force it to close through the task manager, the notification remains on the taskbar in the taskbar.

How can I remove this.

Below is the code:

 //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); } 
+7
source share
4 answers

Catch the exception and discard it in the catch section:

 mNotificationManager.cancel(MY_NOTIFICATION_ID); 
+1
source

I know this question is out of date, but I found it when I had a similar problem. It turned out for me, the service was killed along with the application (which correctly canceled the notification in onDestroy), but then it was restarted (as it should be in START_STICKY), and the notification was sent again. In these cases, I did not want the service to return until the user initiated it from the application, so in OnStartCommand I called stopSelf () when the incoming intent was null.

+1
source

You can override the onDestroy() method and use the NotificationManager to cancel your notification. You only need to specify your notification identifier, which should be canceled.

 @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
source

You can catch errors that violate your application:

 Thread.setDefaultUncaughtExceptionHandler(newHandler); 

Note that doing this will not be able to close your application after an exception, so you need to get the old exceptionHandler link and call it from yours.

Also, add code to remove the notification about this method.

0
source

All Articles