@Tyhj
2018-11-20T11:25:52.000000Z
字数 2679
阅读 1212
Android
Step 1. Add the JitPack repository to your build file
//Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Step 2. Add the dependency
//Add the dependency
dependencies {
implementation 'com.github.tyhjh:CrashUtil:v1.0.1'
}
1.在Application中初始化
CrashHander.getInstance().init(this);
2.自己实现对异常进行处理
CrashUtil.getInstance().setmSaveErro(new ISaveErro() {
@Override
public void saveErroMsg(Throwable throwable) {
//异常处理
}
});
3.或者使用提供的异常保存的本地功能
CrashUtil.getInstance().setmSaveErro(new SaveErroToSDCard(erroPath));
Thread类中有一个getDefaultUncaughtExceptionHandler
方法,可以设置系统默认异常处理器UncaughtExceptionHandler;当未捕获的异常发生的时候,系统会调用UncaughtExceptionHandler的uncaughtException
方法;我们需要实现一个UncaughtExceptionHandler对象,设置为系统默认异常处理器,并在它的uncaughtException
中处理异常信息。
public class CrashUtil implements Thread.UncaughtExceptionHandler {
public static String PHONE_INFO;
ISaveErro mSaveErro;
Context mContext;
private Thread.UncaughtExceptionHandler mDefultCrashHandler;
public static CrashUtil getInstance() {
return CrashHanderHolder.crashHander;
}
public void init(Context context) {
mContext = context.getApplicationContext();
PHONE_INFO = savePhoneInfo(mContext);
mDefultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
public void setmSaveErro(ISaveErro mSaveErro) {
this.mSaveErro = mSaveErro;
}
/**
* 当系统有未捕获的异常,会触发这个方法
*
* @param thread
* @param throwable
*/
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
//对异常进行保存处理
if (!handleException(thread, throwable) && mDefultCrashHandler != null) {
mDefultCrashHandler.uncaughtException(thread, throwable);
} else {
//这里是应该要关闭程序的,异常会导致APP出现问题,ANR黑屏等
android.os.Process.killProcess(android.os.Process.myPid());
}
}
private boolean handleException(Thread thread, Throwable throwable) {
if (thread == null || throwable == null) {
return false;
}
if (mSaveErro != null) {
mSaveErro.saveErroMsg(throwable);
}
return true;
}
static class CrashHanderHolder {
static CrashUtil crashHander = new CrashUtil();
}
// 保存手机的信息
private String savePhoneInfo(Context context) {
PackageManager pm = context.getPackageManager();
PackageInfo pi = null;
try {
pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
StringBuffer phoneMsg = new StringBuffer();
phoneMsg.append("APP Version:")// APP的版本信息
.append(pi.versionName + '_')
.append(pi.versionCode + "\n")
.append("OS Version:") // Android 手机版本号
.append(Build.VERSION.RELEASE + '_')
.append(Build.VERSION.SDK_INT + "\n")
.append("Vendor:")// 手机制造商
.append(Build.MANUFACTURER + "\n")
.append("Model:")// 手机型号
.append(Build.MODEL + "\n")
.append("CUP ABI:" + Build.CPU_ABI + "\n");// CPU架构
return phoneMsg.toString();
}
}
参考:《Android开发艺术探索》