logging program is to facilitate a variety of abnormal situations, in order to facilitate the maintenance of the future maintenance plan, the program can not be hundred health, perfect, it is necessary to save the code in the log. Easy to maintain. Java has an interface Uncaughtexceptionhandler,thread.setdefaultuncaughtexceptionhandler (handler) Sets the default handler that is called when a thread terminates unexpectedly because an exception was not caught, and no other handler is defined for the thread.
So we can inherit Uncaughtexceptionhandler. To read and write logs 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 crash log file */public static file Createcreashlogfile () throws IOException {if (!isexternalstorageavaliable ()) {///??
Check storage can?? 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.
Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.
Android processor Crash Publications