日志记录程序是为了方便各种异常情况,为了方便日后的维修方案进行维修,程序无法百分百健康,完美,有必要保存在日志中代码。易于维护。Java了一个接口UncaughtExceptionHandler,Thread.setDefaultUncaughtExceptionHandler(handler)设置当线程因为未捕获到异常而突然终止,而且没有为该线程定义其它处理程序时所调用的默认处理程序。
所以我们能够继承UncaughtExceptionHandler。 在handler实现对日志的读写
public class CrashHandler implements UncaughtExceptionHandler { // 系统默认的UncaughtException处理 private Thread.UncaughtExceptionHandler mDefaultHandler; public CrashHandler() { mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); } @Override public void uncaughtException(Thread thread, Throwable ex) { try { // 创建日志文件 File file = createCreashLogFile(); // 写入日志文件 if (file != null && file.exists()) { writeLog(file, ex); } } catch (Exception e) { LogUtils.w("", e); } // 将异常抛给系统处?? mDefaultHandler.uncaughtException(thread, ex); } private void writeLog(File logFile, Throwable ex) { PrintStream printStream = null; FileOutputStream fos = null; // 写入日志文件 try { fos = new FileOutputStream(logFile); printStream = new PrintStream(fos); ex.printStackTrace(printStream); } catch (Exception e) { LogUtils.w("", e); } finally { closeQuietly(printStream); closeQuietly(fos); } } private void closeQuietly(OutputStream os) { if (os != null) { try { os.close(); } catch (IOException e) { LogUtils.w("", e); } } } /** 创建??个空白的崩溃日志文件 */ public static File createCreashLogFile() throws IOException { if (!isExternalStorageAvaliable()) { // ?? 查存储是否可?? return null; } File directory = new File(Environment.getExternalStorageDirectory() + "/ViolationQuery/crash_log"); if (!directory.exists()) { directory.mkdirs(); } File file = new File(directory, createCrashLogFileName()); if (file.exists()) { file.delete(); } file.createNewFile(); return file; } /** 存储是否可用 */ public static boolean isExternalStorageAvaliable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } else { return false; } } private static String createCrashLogFileName() { String dateString = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()); return "CrashLog_" + dateString + ".txt"; } }
<pre name="code" class="java">public class CrashManager { public static void start() { // 设置异常处理实例 CrashHandler handler = new CrashHandler(); Thread.setDefaultUncaughtExceptionHandler(handler); } }
然后在Application中调用Application中CrashManager.start();这样就大功告成了
版权声明:本文博主原创文章。博客,未经同意不得转载。
时间: 2024-10-11 13:47:57