android 處理程序crash日志

日志是為瞭方便記錄程序的各種異常情況,方便以後對程序的維護的修補,一個程序不可能做到百分百健壯和完美,所以有必要在代碼中保存日志,方便維護。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";
	}
}
public class CrashManager {
	public static void start() {
		// 設置異常處理實例
		CrashHandler handler = new CrashHandler();
		Thread.setDefaultUncaughtExceptionHandler(handler);
	}
}

 然後在Application中調用Application中CrashManager.start();這樣就大功告成瞭

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *