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:
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);
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.
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!
So far, I have not been able to detect when the app is about to exit. I've tried this:
Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
{
@Override
public void uncaughtException(Thread thread, Throwable ex)
{
notificationManager.cancel(NOTIFICATION_ID);
}
});
And also this:
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
notificationManager.cancel(NOTIFICATION_ID);
}
});
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.
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.
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?
Thanks!
application.onTerminate()is not called. You'll have to find a way to immediately restart your service then manage your notification or flag your notification in a way that the system will remove it when your application is no longer running. - Dan S