Android activity 销毁或应用程序崩溃时删除通知
Android Remove notification when activity destroyed or App crashed
当我的应用程序因任何原因崩溃时 onDestroy()
方法不会被调用。我的通知也没有被删除。当应用程序崩溃时,应该在哪里调用 notifi.cancel(1);
方法来删除通知?
@Override
protected void onDestroy() {
super.onDestroy();
if (nm != null) {
nm.cancel(0);
}
}
onDestory()
方法在系统内存不足或调用 finish()
方法时被调用。所以当你的应用程序崩溃时,不会调用 onDestory()
方法。
check this check this also
where is best position for run notifi.cancel(1); method?
您可以在任何地方调用 notifi.cancel(1);
。这都是需要什么的需求。
不幸的是,当应用程序崩溃时,onDestroy()
没有被调用。要在应用程序崩溃之前获得回调,您应该使用提到的异常处理程序 here。您应该在异常处理程序中编写用于删除通知的代码。
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();
}
});
你也可能想看看这个 very similar question。
当我的应用程序因任何原因崩溃时 onDestroy()
方法不会被调用。我的通知也没有被删除。当应用程序崩溃时,应该在哪里调用 notifi.cancel(1);
方法来删除通知?
@Override
protected void onDestroy() {
super.onDestroy();
if (nm != null) {
nm.cancel(0);
}
}
onDestory()
方法在系统内存不足或调用 finish()
方法时被调用。所以当你的应用程序崩溃时,不会调用 onDestory()
方法。
check this check this also
where is best position for run notifi.cancel(1); method?
您可以在任何地方调用 notifi.cancel(1);
。这都是需要什么的需求。
不幸的是,当应用程序崩溃时,onDestroy()
没有被调用。要在应用程序崩溃之前获得回调,您应该使用提到的异常处理程序 here。您应该在异常处理程序中编写用于删除通知的代码。
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();
}
});
你也可能想看看这个 very similar question。