How to clear a notification if activity fails?

In my application, I create a notification with the FLAG_ONGOING_EVENT flag as such ..

Notification notification = new Notification(iconId, text, System.currentTimeMillis());  
notification.flags |= Notification.FLAG_ONGOING_EVENT;

I cancel the notification in onDestroy, but if my application crashes before calling onDestroy, is there a way to get away from my notification?

Rob W.

+5
source share
3 answers

Everything crashes, even Google apps. I use the Thread.setUncaughtExceptionHandler()following handler code:

package my.package;

import java.lang.Thread.UncaughtExceptionHandler;

import android.app.NotificationManager;
import android.content.Context;

public class CrashHandler implements UncaughtExceptionHandler
{
  private static final int NOTIFICATION_ID = 12345;

  private UncaughtExceptionHandler defaultUEH;
  private NotificationManager notificationManager;

  public CrashHandler(Context context)
  {
    this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  }

  public void uncaughtException(Thread t, Throwable e)
  {
    if (notificationManager != null)
    {
      try
      {
        notificationManager.cancel(NOTIFICATION_ID);
      }
      catch (Throwable ex)
      {
        ex.printStackTrace();
      }
    }
    notificationManager = null;

    defaultUEH.uncaughtException(t, e);
  }
}
+17
source

Is this more or less the same question as the Callback before Force Close activity of Android? so I will repeat my answer here:

, . -, COULD crash, / .

, try/catch, Thread.setUncaughtExceptionHandler(). , Runtime.addShutdownHook, , , .

. .

+5

. , ! ( catch Exception e {...} - ), ( , ).

+2

All Articles