Home » Android » android – Clear notification in status bar after application crashed

android – Clear notification in status bar after application crashed

Posted by: admin June 15, 2020 Leave a comment

Questions:

In my application I have several services running. When user stop application (UI part) services remain running in the background and display notifications ( each service has one) in status bar. When clicking on it dialog appears with choice to cancel appropriate service.

And here is my problem. When something goes wrong and application crashes notifications remains in the status bar area. Is it possible to clear all notifications before showing standard android force close dialog?

The real bug is NPE when I try to open activity clicking on notification. It’s fixed. But I only want to know how to clear everything when application crashes.


Here is my final solution inspired by mice’s post. In application in on create method I register Thread.setDefaultUncaughtExceptionHandler()

@Override
public void onCreate() {
    super.onCreate();
    this.notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    final UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    UncaughtExceptionHandler appHandler = new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            this.notificationManager.cancelAll();
            defaultHandler.uncaughtException(thread, ex);
        }
    };
    Thread.setDefaultUncaughtExceptionHandler(appHandler);
}

thanks

How to&Answers:

You may call

Thread.setDefaultUncaughtExceptionHandler()

with a handler to be called when some Exception is not handled by your app in the thread.
This handler is invoked in case Thread dies due to an unhandled exception.

Here you’d do needed cleanup work.

This is exactly how ACRA crash reporting library is catching crashes.

Answer:

First thing you need to ensure that your application should not get crashed at any cost and answer to your question, you should override onDestroy() method of the service and cancel notification there as it will work for you in both the cases when service stops or it crashes.

As you can not use onDestroy() in case of crash, so you need to put try catch block and after getting exception perform your appropriate action.