日志是为了方便记录程序的各种异常情况,方便以后对程序的维护的修补,一个程序不可能做到百分百健壮和完美,所以有必要在代码中保存日志,方便维护。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-07 06:45:11