UncaughtExceptionHandler

/**
 * 崩溃信息处理
 * Created by travis on 2016/1/21.
 */
public class VIIUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
    private static final String TAG = VIIUncaughtExceptionHandler.class.getSimpleName();
    private Thread.UncaughtExceptionHandler mDefaultUncaughtExceptionHandler;


    public VIIUncaughtExceptionHandler() {
        this.mDefaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        final Writer writer = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(writer);

        StackTraceElement[] trace = ex.getStackTrace();
        StackTraceElement[] tem = new StackTraceElement[trace.length + 3];
        System.arraycopy(trace, 0, tem, 0, trace.length);
        tem[trace.length] = new StackTraceElement("android", "MODEL", Build.MODEL, -1);
        tem[trace.length + 1] = new StackTraceElement("android", "VERSION", Build.VERSION.RELEASE, -1);
        tem[trace.length + 2] = new StackTraceElement("android", "FINGERPRINT", Build.FINGERPRINT, -1);
        ex.setStackTrace(trace);
        ex.printStackTrace(printWriter);
        String dung = writer.toString();
        printWriter.close();
        collectDung(dung);

        mDefaultUncaughtExceptionHandler.uncaughtException(thread, ex);
    }

    private void collectDung(String dung) {
        upload(dung);
        store(dung);
    }

    /**
     * 把错误信息上传到服务器
     *
     * @param dung
     */
    private void upload(String dung) {

    }

    /**
     * 把错误信息保存到本地
     */
    private void store(String dung) {
        if (FileUtils.isExternalStorageMounted()) {
            File root = new File(Environment.getExternalStorageDirectory() + AppConfig.root);
            if (!root.exists()) {
                root.mkdirs();
            }
            File file = new File(root, AppConfig.log.substring(AppConfig.log.lastIndexOf("/") + 1));
            BufferedWriter writer = null;
            try {
                writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
                writer.write(TimeUtils.getCurrentTime());
                writer.newLine();
                writer.write(dung);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (writer != null) {
                    try {
                        writer.flush();
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
原文地址:https://www.cnblogs.com/hsji/p/5148794.html