public class AppApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
CrashProtectManager.getInstance(this).init();
}
}
public class CrashProtectManager {
private static CrashProtectManager mInstance;
private static Context mContext;
private CrashProtectManager() {
}
public static CrashProtectManager getInstance(Context context) {
if (mInstance == null) {
mContext = context.getApplicationContext();
mInstance = new CrashProtectManager();
}
return mInstance;
}
public void init() {
//crach 防护
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
handleFileException(e);
if (t == Looper.getMainLooper().getThread()) {
handleMainThread(e);
}
}
});
}
//日志文件系统
private void handleFileException(Throwable e) {
//通过Throwable 生成字符串
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
e.printStackTrace(printWriter);
printWriter.close();
String result = writer.toString();
//定义文件名
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String time = dateFormat.format(new Date());
String fileName = "crash-" + time + ".txt";
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File cacheDir = mContext.getCacheDir();
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
File cacheFile = new File(cacheDir.getAbsolutePath(), fileName);
if (!cacheDir.exists()) {
cacheFile.createNewFile();
}
//把字符串写入到文件
FileOutputStream outputStream = new FileOutputStream(cacheFile);
outputStream.write(result.getBytes());
outputStream.close();
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
private void handleMainThread(Throwable e) {
while (true) {
try {
Looper.loop();
} catch (Throwable e1) {
handleFileException(e1);
}
}
}
}
网友评论