崩溃日志的捕获有很多种方式,最直接的就是接入三方的捕获,但是由于某些原因或者说某些原因导致不能准确的定位到崩溃的位置,也为了使应用程序测试时更好的定位崩溃位置(测试机多的时候不可能每个都去打LOG和断点)
其实原理很简单,应用出现异常后,会由默认的异常处理器来处理异常,我们要做的就是把这个任务接管过来,自己处理异常,包括收集日志,保存到本地,然后上传到服务器。
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Date;
/**
* <p>类描述:异常捕获处理器
* @author ma
*/
public class CrashHandler implements UncaughtExceptionHandler {
//每个小时的日志都是记录在同一个文件
private final static String LOG_FILE_CREATE_TIME_FORMAT = "yyyy-MM-dd_HH";
private final static String LOG_FILE_SUFFIX = "_crash.log";
//日志记入的时间
private final static String LOG_RECORD_TIME_FORMAT ="yyyy-MM-dd HH:mm:ss";
private UncaughtExceptionHanlderListener mHanlderListener;
private Context mContext;
private static CrashHandler sInstance;
//设置日志所在文件夹路径
private String mLogDir;
private StringBuffer sb;
public static CrashHandler getInstance(Context context){
if (sInstance == null) {
sInstance = new CrashHandler(context);
}
return sInstance;
}
private CrashHandler(Context context){
mContext = context;
Thread.setDefaultUncaughtExceptionHandler(this);
}
/* (non-Javadoc)
* @see java.lang.Thread.UncaughtExceptionHandler#uncaughtException(java.lang.Thread, java.lang.Throwable)
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
Log.e("ssssssssss","cuowu1");
hanldeException(ex);
if (mHanlderListener != null) {
mHanlderListener.handlerUncaughtException(sb);
}
}
/**
* 设置外部要处理异常发生时操作监听器
* @param hanlderListener : {@link UncaughtExceptionHanlderListener}
*/
public void setHanlderListener(UncaughtExceptionHanlderListener hanlderListener) {
this.mHanlderListener = hanlderListener;
}
/**
* 设置日志所在文件夹路径
* @param logDirPath
*/
public void setCrashLogDir(String logDirPath){
mLogDir = logDirPath;
}
//崩溃日志的保存操作
private void hanldeException(Throwable ex){
Log.e("ssssssssss","cuowu2");
if (ex == null) {
return ;
}
if (CrashUtils.isSDCardAvaiable(mContext) && !TextUtils.isEmpty(mLogDir)) {
saveCrashInfoToFile(ex);
}
}
//保存错误信息到文件中
private void saveCrashInfoToFile(Throwable ex) {
Writer info = new StringWriter();
PrintWriter printWriter = new PrintWriter(info);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {