最近在調試安卓程序,因爲某些緣由調試時手機不能鏈接PC端,沒法經過IDE查看程序崩潰的Log,但願log可以寫入文件中,對於已經發布的App能夠經過該功能收集Bugjava
package com.zxl.crash; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.lang.Thread.UncaughtExceptionHandler; public class MyCrashHandler implements UncaughtExceptionHandler{ private static MyCrashHandler crashHandler; @Override public void uncaughtException(Thread thread, Throwable ex) { // TODO Auto-generated method stub if (crashHandler != null) { try { //將crash log寫入文件 FileOutputStream fileOutputStream = new FileOutputStream("/mnt/sdcard/crash_log.txt", true); PrintStream printStream = new PrintStream(fileOutputStream); ex.printStackTrace(printStream); printStream.flush(); printStream.close(); fileOutputStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //設置默認處理器 public void init() { Thread.setDefaultUncaughtExceptionHandler(this); } private MyCrashHandler() {} //單例 public static MyCrashHandler instance() { if (crashHandler == null) { synchronized (crashHandler) { crashHandler = new MyCrashHandler(); } } return crashHandler; } }