package com.hh.arome.utlis.log;

import android.content.Context;
import android.util.Log;


public class CrashLogManager implements Thread.UncaughtExceptionHandler {
    //系统默认的UncaughtException处理类
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    //CrashLogManager实例
    private static CrashLogManager INSTANCE = new CrashLogManager();
    //程序的Context对象
    private Context mContext;

    /**
     * 保证只有一个CrashLogManager实例
     */
    private CrashLogManager() {
    }

    /**
     * 获取CrashLogManager实例 ,单例模式
     */
    public static CrashLogManager getInstance() {
        return INSTANCE;
    }

    /**
     * 初始化
     *
     * @param context
     */
    public void init(Context context) {
        mContext = context;
        //获取系统默认的UncaughtException处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        //设置该CrashLogManager为程序的默认处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    /**
     * 最关键函数，当程序有未捕获的异常时，系统自动调用次方法
     *
     * @param thread 未捕获异常线程
     * @param ex     未捕获异常信息
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {

        AppLogUtils.e("uncaughtException");

        String stackTraceString = Log.getStackTraceString(ex);
        AppLogUtils.saveLog(LogType.Crash, stackTraceString);
        if (mDefaultHandler != null) {
            //如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }
    }

}