Android的UncaughtExceptionHandle处理和Crash异常信息收集后台ACRA、acralyzer
public static final String TAG = “CrashHandler”;
// CrashHandler实例
private static CrashManager instance;
// 程序的Context对象
private Application application;
// 系统默认的UncaughtException处理类
private UncaughtExceptionHandler mDefaultHandler;
/**
* 保证只有一个CrashHandler实例
*/
private CrashManager(Context context) {
application = (Application) context.getApplicationContext();
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
/**
* 获取CrashHandler实例 ,单例模式
*/
public static CrashManager getInstance(Context context) {
CrashManager inst = instance;
if (inst == null) {
synchronized (CrashManager.class) {
inst = instance;
if (inst == null) {
inst = new CrashManager(context.getApplicationContext());
instance = inst;
}
}
}
return inst;
}
/**
* 当UncaughtException发生时会转入该函数来处理
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
TaskManager.getInstance(application).saveErrorLog(ex);
mDefaultHandler.uncaughtException(thread, ex);
}
private SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd-HH-mm-ss”, Locale.CHINA);
private Context context;
private Throwable ex;
public SaveErrorTask(Context context, Throwable ex) {
setPriority(TaskPriority.UI_LOW);
this.context = context;
this.ex = ex;
}
@Override
protected Void doInBackground(Object… arg0) {
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
printWriter.close();
String result = writer.toString();
String time = formatter.format(new Date());
String fileName = time + “.txt”;
StringBuilder stringBuffer = new StringBuilder();
DeviceInfo deviceInfo = Utils.getDeviceInfo(context);
stringBuffer.append(“\nsdkVersion:” + deviceInfo.sdkVersion);
stringBuffer.append(“\nmanufacturer:” + deviceInfo.manufacturer);
stringBuffer.append(“\nmodel:” + deviceInfo.model);
stringBuffer.append(“\nversion” + ConfigManager.getVersionName(context));
stringBuffer.append(“\nerrorStr:” + result);
stringBuffer.append(“\ntime:” + time);
String filePath = CacheFileUtils.getLogPath(fileName);
CacheFileUtils.saveErrorStr(filePath, stringBuffer.toString());
return null;
}
@Override
public void on
super.on
//初始化 错误日子系统
CrashManager.getInstance(this);
}