1

When my app crashes for any reason onDestroy() method is not called. My notification is also not removed. Where should notifi.cancel(1); method be called to remove the notification whenever the app crashes?

@Override
protected void onDestroy() {
    super.onDestroy();

    if (nm != null) {
        nm.cancel(0);
    }

}
Antrromet
  • 15,294
  • 10
  • 60
  • 75
Farzad
  • 1,975
  • 1
  • 25
  • 47

2 Answers2

4

Unfortunately onDestroy() is not called when the app is crashed. To get a callback before the app is crashed, you should use an Exception Handler as mentioned here. You should write the code for removing the notification in an Exception Handler.

Thread.currentThread().setUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            new Thread() {
                @Override
                public void run() {
                    Looper.prepare();  
                    // Cancel Notification
                    if (nm != null) {
                        nm.cancel(0);
                    }
                    Looper.loop();
                }
            }.start();
        }
    });

Also you might want to take a look at this very similar question.

Community
  • 1
  • 1
Antrromet
  • 15,294
  • 10
  • 60
  • 75
0

onDestory() method is called when system is low memory or when you call finish() method. So when your app crashed, will not call onDestory() method. check this check this also

where is best position for run notifi.cancel(1); method?

You can call any where notifi.cancel(1);. This all demand on what is needed.

Community
  • 1
  • 1
mubeen
  • 813
  • 2
  • 18
  • 39
  • if app crashed, How do I cancel notifications? – Farzad Aug 15 '15 at 19:07
  • 1
    The question asked is about the place to call the `notifi.cancel(1)` method when the app crashes, and your answer is incorrect. You cannot just call it anywhere. Its supposed to be called only when the app crashes. – Antrromet Aug 15 '15 at 19:19
  • 1
    app crash is cause by exception when not handled and it is not good thing. you should catch the exception and you can call in catch block notifi.cancel(1) – mubeen Aug 15 '15 at 19:19
  • 1
    _Everything crashes, even Google applications do._ http://stackoverflow.com/a/4598457/451951 – Antrromet Aug 15 '15 at 19:21