CrashHandler捕获全局异常

public class CrashHandler implements UncaughtExceptionHandler {
   public static final String TAG = "CrashHandler";
   private static CrashHandler INSTANCE = new CrashHandler();
   private UncaughtExceptionHandler mDefaultHandler;
   private CrashHandler() {
   }

   public static CrashHandler getInstance() {
      return INSTANCE;
   }

   public void init(Context context) {
      mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
      Thread.setDefaultUncaughtExceptionHandler(this);
   }

   /**  * UncaughtException发生时会转入该函数来处理  */  @Override
   public void uncaughtException(Thread thread, Throwable exception) {
      final Writer result = new StringWriter();
      final PrintWriter printWriter = new PrintWriter(result);
      exception.printStackTrace(printWriter);
      LogUtil.log("app uncaughtException:" + result.toString());
      printWriter.close();
      mDefaultHandler.uncaughtException(thread, exception);
   }

}
 
 
使用可以在继承的application类中onCreat:
CrashHandler crashHandler = CrashHandler.getInstance();
crashHandler.init(getApplicationContext());
这样可以将抛出的异常存入在文件中。

你可能感兴趣的:(CrashHandler捕获全局异常)