package com.bbitcn.silk.utils.log;


import android.content.Context;
import android.content.Intent;

public class CrashHandlerUtil implements Thread.UncaughtExceptionHandler {
    /**
     * 饿汉式单例模式
     */
    private static CrashHandlerUtil crashHandlerUtil = new CrashHandlerUtil();
    private Thread.UncaughtExceptionHandler mDefaultCaughtExceptionHandler;
    private Context mContext;

    private CrashHandlerUtil() {
        // 私有构造函数，确保单例模式
    }

    public static CrashHandlerUtil getInstance() {
        return crashHandlerUtil;
    }

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

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        ex.printStackTrace();
        MyLog.appError("软件已崩溃,重启应用：" + getFormattedException(ex));
        Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(mContext.getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        mContext.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    /**
     * 格式化异常信息的方法
     */
    public String getFormattedException(Throwable throwable) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("异常详情：\n")
                .append("异常类型：").append(throwable.getClass().getName()).append("\n")
                .append("异常消息：").append(throwable.getMessage()).append("\n");
        StackTraceElement[] stackTrace = throwable.getStackTrace();
        if (stackTrace != null && stackTrace.length > 0) {
            stringBuilder.append("异常位置：").append(stackTrace[0].toString()).append("\n");
        }

        stringBuilder.append("完整堆栈跟踪：\n");
        for (StackTraceElement element : stackTrace) {
            stringBuilder.append("\t").append(element.toString()).append("\n");
        }

        return stringBuilder.toString();
    }

}