Android 全局异常捕捉 + 本地异常日志

public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static final Format FORMAT = new SimpleDateFormat("yy-MM-dd HH-mm-ss",Locale.getDefault());                         

    private static CrashHandler instance = null;
    private Thread.UncaughtExceptionHandler defaultHandler;
    private Context context;

    public static CrashHandler getInstance() {
        if (instance == null) {
            synchronized (CrashHandler.class) {
                if (instance == null) {
                    synchronized (CrashHandler.class) {
                        instance = new CrashHandler();
                    }
                }
            }
        }
        return instance;
    }

    private CrashHandler() {
    }

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

    @Override
    public void uncaughtException(final Thread t, final Throwable e) {
        if (e == null) {
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                saveCrashToLocal(t,e);
            }
        }).start();
    }

    private void saveCrashToLocal(Thread t,final Throwable e){
        Date now = new Date(System.currentTimeMillis());
        String fileName = "crash_" + FORMAT.format(now) + ".log";
        final String fullPath = FileUtil.getInstance().getCrashPath() + "/" + fileName;
        FileUtil.getInstance().createNewFile(fullPath);

        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new FileWriter(fullPath, false));
            e.printStackTrace(pw);
            Throwable cause = e.getCause();
            while (cause != null) {
                cause.printStackTrace(pw);
                cause = cause.getCause();
            }
        } catch (IOException exc) {
            exc.printStackTrace();
        } finally {
            if (pw != null) {
                pw.close();
            }
        }

        if (defaultHandler != null) {
            defaultHandler.uncaughtException(t, e);
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值