android 處理常式crash日誌

來源:互聯網
上載者:User

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();這樣就大功告成了

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.