Android全局异常捕获

全局异常捕获是个经常会用到的工具类

下面这段代码可以直接放入项目中使用

/**
 * 全局异常捕获句柄类
 */
public class CrashHandler implements UncaughtExceptionHandler {

    public static final String TAG = CrashHandler.class.getName();

    private static CrashHandler mInstance;

    private Thread.UncaughtExceptionHandler mSystemExceptionHandler; // 系统默认的UncaughtExceptionHandler
    private Context mContext;

    /**
     * 私有构造函数
     */
    private CrashHandler() {
    }

    /**
     * @return 单例
     */
    public static CrashHandler getInstance() {
        if (mInstance == null) {
            mInstance = new CrashHandler();
        }
        return mInstance;
    }

    /**
     * @param context 上下文对象
     */
    public void init(Context context) {
        mContext = context;
        mSystemExceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); // 获取系统默认的UncaughtExceptionHandler
        Thread.setDefaultUncaughtExceptionHandler(this); // 设置本类对象crashHandler为程序的默认处理器
    }

    /**
     * 当异常发生时,捕获异常
     *
     * @param thread 线程
     * @param ex     异常
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        try {
            handleException(thread, ex);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
            if (mSystemExceptionHandler != null) {
                mSystemExceptionHandler.uncaughtException(thread, ex); // 让系统默认的异常处理器来处理
            }
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            Log.e(TAG, e.getMessage(), e);
        }
        MainApplication.getInstance().stopService();
        MainApplication.getInstance().restartApp();
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(10);
    }

    /**
     * 自定义异常处理
     *
     * @param ex 异常
     */
    private void handleException(Thread thread, Throwable ex) {
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);

        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();

        String info = writer.toString();
        Log.e(TAG, info);

        FileUtils.saveLog("=================CrashInfo===============");
        FileUtils.saveLog(info);
        FileUtils.saveLog("================CrashInfoEnd=============");
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值