开发者

Clear notification in status bar after application crashed

开发者 https://www.devze.com 2023-04-09 06:07 出处:网络
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

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();
    UncaughtExceptionHandl开发者_StackOverflower appHandler = new UncaughtExceptionHandler() {

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

thanks


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消