程序崩溃处理

public class CrashHandler implements Thread.UncaughtExceptionHandler {

   public static CrashHandler mAppCrashHandler;

   private Thread.UncaughtExceptionHandler mDefaultHandler;

   private MyApplication mAppContext;

   public void initCrashHandler(MyApplication application) {
      this.mAppContext = application;
      // 获取系统默认的UncaughtException处理器
      mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
      Thread.setDefaultUncaughtExceptionHandler(this);
   }

   public static CrashHandler getInstance() {
      if (mAppCrashHandler == null) {
         mAppCrashHandler = new CrashHandler();
      }
      return mAppCrashHandler;
   }

   @Override
   public void uncaughtException(Thread thread, Throwable ex) {
      if (!handleException(ex) && mDefaultHandler != null) {
         // 如果用户没有处理则让系统默认的异常处理器来处理
         mDefaultHandler.uncaughtException(thread, ex);
      } else {
         AlarmManager mgr = (AlarmManager) mAppContext.getSystemService(Context.ALARM_SERVICE);

         Intent intent = new Intent(mAppContext, WelcomeActivity.class);
         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         intent.putExtra("crash", true);
         PendingIntent restartIntent = PendingIntent.getActivity(mAppContext, 0, intent, PendingIntent.FLAG_ONE_SHOT);
         mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用

         android.os.Process.killProcess(android.os.Process.myPid());
         System.exit(0);
         System.gc();
      }
   }

   /**
    * 错误处理,收集错误信息 发送错误报告等操作均在此完成.
    * @param ex
    * @return true:如果处理了该异常信息;否则返回false.
    */
   private boolean handleException(Throwable ex) {
      if (ex == null) {
         return false;
      }
      // 自定义处理错误信息
      return true;
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值