log is to facilitate the recording of various anomalies of the program, easy to repair the maintenance of the program later, a program can not be hundred-percent robust and perfect, so it is necessary to save the log in the code, easy to maintain. The Java Threading class provides an interface Uncaughtexceptionhandler,thread.setdefaultuncaughtexceptionhandler (handler) Sets the default handler that is called when a thread is abruptly terminated because it did not catch an exception, and no other handlers are defined for the thread.
So we can inherit Uncaughtexceptionhandler and read and write the log in handler .
public class Crashhandler implements Uncaughtexceptionhandler {//system default Uncaughtexception handling private Thread.uncaughtexceptionhandler mdefaulthandler;public Crashhandler () {Mdefaulthandler = Thread.getdefaultuncaughtexceptionhandler ();} @Overridepublic void uncaughtexception (thread thread, throwable ex) {try {//create logfile file = Createcreashlogfile ();//write 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 log file try {fos = new FileOutputStream (logFile);p rintstream = new PrintStream (FOS); ex.print StackTrace (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 );}}} /** create?? A blank collapse.Crash log files */public static file Createcreashlogfile () throws IOException {if (!isexternalstorageavaliable ()) {///?? Is it possible to check the storage?? return null;} File directory = new file (environment.getexternalstoragedirectory () + "/violationquery/crash_log"); Directory.Exists ()) {directory.mkdirs ();} File File = new file (directory, Createcrashlogfilename ()), if (File.exists ()) {File.delete ();} File.createnewfile (); return file;} /** storage is available */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";}}
<pre name= "code" class= "Java" >public class Crashmanager {public static void start () {//Set exception handling instance Crashhandler handle R = new Crashhandler (); Thread.setdefaultuncaughtexceptionhandler (handler);}}
Then in the application Call application in Crashmanager.start (); that's it.
Android Handler crash log