1. 程式人生 > >Android 全域性異常捕捉 + 本地異常日誌

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);
        }
    }
}