android 處理常式crash日誌
日誌是為了方便記錄程式的各種異常情況,方便以後對程式的維護的修補,一個程式不可能做到百分百健壯和完美,所以有必要在代碼中儲存日誌,方便維護。Java線程類提供了一個介面UncaughtExceptionHandler,Thread.setDefaultUncaughtExceptionHandler(handler)設定當線程由於未捕獲到異常而突然終止,並且沒有為該線程定義其他處理常式時所調用的預設處理常式。
所以我們可以繼承UncaughtExceptionHandler, 在handler實現對日誌的讀寫
public class CrashHandler implements UncaughtExceptionHandler {// 系統預設的UncaughtException處理private Thread.UncaughtExceptionHandler mDefaultHandler;public CrashHandler() {mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();}@Overridepublic 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";}}
public class CrashManager {public static void start() {// 設定異常處理執行個體CrashHandler handler = new CrashHandler();Thread.setDefaultUncaughtExceptionHandler(handler);}}
然後在Application中調用Application中CrashManager.start();這樣就大功告成了