Android: catching application exit
<p>I'm currently building an app that will play sounds. When a user starts a sound, I display a status bar notification with this code:</p>

<pre>
notificationManager = (NotificationManager) activity.getSystemService(Activity.NOTIFICATION_SERVICE);

Intent intent = new Intent(activity, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0);

notification = new Notification();
notification.icon = android.R.drawable.stat_notify_sync;
notification.flags |= Notification.FLAG_ONGOING_EVENT;

String title = activity.getString(R.string.notification_title);
String text = activity.getString(R.string.notification_text);

notification.setLatestEventInfo(activity, title, text, pendingIntent);
</pre>

<p>This is working fine. Later, if the user stops all sound, I use notificationManager.cancel to remove the notification, and again, this is working fine.</p>

<p>My problem is that I want to handle the case of someone using a task killer app. If someone uses one to kill my app, I'd like the notification icon to be removed from the status bar. I know that a lot of users like to use those kind of apps and I don't want some to complain that they can't "close" my app!</p>

<p>So far, I have not been able to detect when the app is about to exit. I've tried this:</p>

<pre>
Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
{
  @Override
  public void uncaughtException(Thread thread, Throwable ex)
  {
    notificationManager.cancel(NOTIFICATION_ID);
  }
});
</pre>

<p>And also this:</p>

<pre>
Runtime.getRuntime().addShutdownHook(new Thread()
{
  @Override
  public void run()
  {
     notificationManager.cancel(NOTIFICATION_ID);              
  }
});
</pre>

<p>But this is not working. When my app gets killed, the notification icon is still there. To kill my app, I've been using an app called "Advanced Task Killer". I've also test by killing  my process within DDMS.</p>

<p>I've noticed that the native media player is doing that. If a music is playing and you kill the music service, the icon will disappear.</p>

<p>So, is there a way to detect when an application is about to exit so that I can remove the notification icon? Or is there a way for the notification icon to be removed automatically if my app is killed?</p>

<p>Thanks!</p>
