简体   繁体   中英

Android Remove notification when activity destroyed or App crashed

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);
    }

}

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM