2016-12-10 26 views
0

我有一个应用程序,由于很多原因可能会崩溃。我想的是,当应用程序崩溃,也应该删除所有相关的通知:Android当应用程序崩溃时清理所有通知

public class CrashHandler implements UncaughtExceptionHandler { 

    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.cancelAll(); 

      } catch (Throwable ex) { 
       ex.printStackTrace(); 
      } 
     } 

     notificationManager = null; 
     defaultUEH.uncaughtException(t, e); 
    } 
} 

,并在我的主要活动我叫上面的类:

new CrashHandler(context); 

但是当我运行应用程序,应用程序崩溃的通知不会被删除!任何想法?

+0

而不是让自己陷入崩溃,你应该看看**为什么**崩溃。如果应用程序崩溃,在大多数情况下,您将无法执行方法。如果它崩溃,它会突然完成。我读了一些有关的东西,你可以通过注册一个服务并在服务onDestroy()中执行该方法来做一些技巧。但如果真的有帮助,我从来没有测试过。 – Opiatefuchs

回答

0

您需要在您的应用程序类中使用setDefaultUncaughtExceptionHandler,如下所示。

public class MyApplication extends Application { 

    @Override 
    public void onCreate() { 
     // Set your custom UncaughtExceptionHandler 
     Thread.setDefaultUncaughtExceptionHandler(new CrashHandler()); 

     super.onCreate(); 
    } 
} 

在您的AndroidMenifest.xml文件中,将Application类设置为name属性。

<application 
    android:name=".MyApplication" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppBaseTheme"> 

后,当您的应用程序会崩溃,由于未捕获的异常,应用程序崩溃之前uncaughtException(Thread t, Throwable e)方法将被调用你的CrashHandler类。

+0

感谢您的回复!我检查它并让你知道 – Shoaib