Android如何防止异常奔溃以及拿到crash日志,处理线上问题定位
16lz
2021-01-23
Android中防止程序崩溃,以及拿到crash日志分析定位
1.添加该工具类方法
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); } } }}
2.在application中的onCreate()初始化
CrashProtectManager.getInstance(this).init();
3.日志生成的文件在
data/data/packagename/cahe 目录下
更多相关文章
- Android 制定的ROM包(文件系统根目录结构分析)
- Android中xml文件读写
- Android中Manifest.xml配置文件
- android之layout配置文件解读
- android 从tomcat读取文件出错:connect failed: ECONNREFUSED
- Android:dimen尺寸资源文件的使用
- Android中五中布局文件的使用和介绍
- android 读取assets指定文件