Android handler crash log
Logs are used to easily record various exceptions of the program and facilitate the repair of program maintenance in the future. It is impossible for a program to be robust and perfect. Therefore, it is necessary to save logs in the Code for easy maintenance. The Java Thread class provides an interface UncaughtExceptionHandler, Thread. setDefaultUncaughtExceptionHandler (handler) is used to set the default handler called when the thread is suddenly terminated because no exception is caught and no other handler is defined for the thread.
Therefore, we can inherit UncaughtExceptionHandler to read and write logs in handler.
Public class CrashHandler implements UncaughtExceptionHandler {// the system's default UncaughtException processes private threads. uncaughtExceptionHandler mDefaultHandler; public CrashHandler () {mDefaultHandler = Thread. getDefaultUncaughtExceptionHandler () ;}@ Overridepublic void uncaughtException (Thread thread, Throwable ex) {try {// create a log File file = createCreashLogFile (); // write a log File if (file! = Null & file. exists () {writeLog (file, ex) ;}} catch (Exception e) {LogUtils. w ("", e) ;}// throw an exception to the system ?? MDefaultHandler. uncaughtException (thread, ex);} private void writeLog (File logFile, Throwable ex) {PrintStream printStream = null; FileOutputStream fos = null; // write the log file 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 (Ou TputStream OS) {if (OS! = Null) {try {OS. close () ;}catch (IOException e) {LogUtils. w ("", e) ;}}/ ** create ?? Empty crash log files */public static File createCreashLogFile () throws IOException {if (! IsExternalStorageAvaliable ()){//?? Is storage available ?? 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;}/** storage availability */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 () {// sets the CrashHandler handler = new CrashHandler (); Thread. setDefaultUncaughtExceptionHandler (handler );}}
Then, in the Application, call CrashManager. start ();.