异常捕获的demo文件-------结合腾讯bugly

异常捕获的demo文件

public class CrashHandler implements Thread.UncaughtExceptionHandler {

private static CrashHandler sInstance = null;
private Thread.UncaughtExceptionHandler mDefaultHandler;
private Context mContext;
// 保存手机信息和异常信息
private Map<String, String> mMessage = new HashMap<>();

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

private CrashHandler() {
}

/**
 * 初始化默认异常捕获
 *
 * @param context context
 */
public void init(Context context) {
    mContext = context;
    // 获取默认异常处理器
    mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    // 将此类设为默认异常处理器
    Thread.setDefaultUncaughtExceptionHandler(this);
}

@Override
public void uncaughtException(Thread t, Throwable e) {
    if (!handleException(e)) {
        // 未经过人为处理,则调用系统默认处理异常,弹出系统强制关闭的对话框
        if (mDefaultHandler != null) {
            mDefaultHandler.uncaughtException(t, e);
        }
    } else {
        // 已经人为处理,系统自己退出
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        System.exit(1);
    }
}

/**
 * 是否人为捕获异常
 *
 * @param e Throwable
 * @return true:已处理 false:未处理
 */
private boolean handleException(Throwable e) {
    if (e == null) {// 异常是否为空
        return false;
    }
    new Thread() {// 在主线程中弹出提示
        @Override
        public void run() {
            Looper.prepare();
            Toast.makeText(mContext, "捕获到异常", Toast.LENGTH_SHORT).show();
            Looper.loop();
        }
    }.start();
    collectErrorMessages();
    saveErrorMessages(e);
    return false;
}

/**
 * 1.收集错误信息
 */
private void collectErrorMessages() {
    PackageManager pm = mContext.getPackageManager();
    try {
        PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
        if (pi != null) {
            String versionName = TextUtils.isEmpty(pi.versionName) ? "null" : pi.versionName;
            String versionCode = "" + pi.versionCode;
            mMessage.put("versionName", versionName);
            mMessage.put("versionCode", versionCode);
        }
        // 通过反射拿到错误信息
        Field[] fields = Build.class.getFields();
        if (fields != null && fields.length > 0) {
            for (Field field : fields) {
                field.setAccessible(true);
                try {
                    mMessage.put(field.getName(), field.get(null).toString());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
}

/**
 * 2.保存错误信息
 *
 * @param e Throwable
 */
private void saveErrorMessages(Throwable e) {
    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, String> entry : mMessage.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        sb.append(key).append("=").append(value).append("\n");
    }
    Writer writer = new StringWriter();
    PrintWriter pw = new PrintWriter(writer);
    e.printStackTrace(pw);
    pw.close();
    String result = writer.toString();
    sb.append(result);
    String fileName = "crash.log";
    // 有无SD卡
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        String path = Environment.getExternalStorageDirectory().getPath() + "/crash/";
        File dir = new File(path);
        if (!dir.exists()) dir.mkdirs();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(path + fileName);
            fos.write(sb.toString().getBytes());
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}
}

全局配置的Application

public class EHApplication extends Application {

private static Context context;

@Override
public void onCreate() {
    super.onCreate();
    CrashHandler.getInstance().init(this);
    context = this;
    CrashReport.initCrashReport(getApplicationContext(), "e2637b4948", false);
}

public static Context getContext() {
    return context;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值