Crashhandler for Android

Source: Internet
Author: User

 PackageCom.envy15.cherry.sys.log;ImportAndroid.annotation.SuppressLint;ImportAndroid.content.Context;ImportAndroid.content.pm.PackageInfo;ImportAndroid.content.pm.PackageManager;ImportAndroid.os.Build;Importandroid.os.Environment;ImportAndroid.os.Looper;ImportAndroid.os.SystemClock;ImportAndroid.util.Log;ImportAndroid.widget.Toast;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.PrintWriter;ImportJava.io.StringWriter;ImportJava.io.Writer;ImportJava.lang.reflect.Field;ImportJava.text.DateFormat;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportJava.util.HashMap;ImportJava.util.Map;/*** Created by ENVY15 on 2016/10/30. * Crash Log record * Reference: *http://blog.csdn.net/u012333411/article/details/49019415 *  http://blog.csdn.net/wangyuexing_blog/article/details/39009069crashhandler.getinstance (). Init (this); */@SuppressLint ("SimpleDateFormat") Public classCrashhandlerImplementsThread.uncaughtexceptionhandler { Public StaticString TAG = "Cherrycrash"; //system default Uncaughtexception processing class    PrivateThread.uncaughtexceptionhandler Mdefaulthandler; Private StaticCrashhandler instance =NewCrashhandler (); PrivateContext Mcontext; //used to store device information and exception information    Privatemap<string, string> errinfo =NewHashmap<string, string>(); //used to format the date as part of the log file name    PrivateDateFormat formatter =NewSimpleDateFormat ("Yyyy-mm-dd"); /*** Guaranteed only one Crashhandler instance*/    PrivateCrashhandler () {}/*** Get Crashhandler instances, Singleton mode*/     Public StaticCrashhandler getinstance () {returninstance; }    /*** Initialize * *@paramContext*/     Public voidinit (Context context) {Mcontext=context; //get the system default Uncaughtexception processorMdefaulthandler =Thread.getdefaultuncaughtexceptionhandler (); //set the Crashhandler as the default processor for the programThread.setdefaultuncaughtexceptionhandler ( This); Autoclear (5); }    /*** When uncaughtexception occurs, it is transferred to the function to handle*/@Override Public voiduncaughtexception (thread thread, Throwable ex) {if(!handleexception (ex) && Mdefaulthandler! =NULL) {            //let the system default exception handler handle if the user does not handlemdefaulthandler.uncaughtexception (thread, ex); } Else{systemclock.sleep (3000); //Exit Programandroid.os.Process.killProcess (Android.os.Process.myPid ()); System.exit (1); }    }    /*** Custom error handling, collect error messages to send error reports and so on are done here. *     * @paramex *@returntrue: Returns False if the exception information is processed; */    Private BooleanHandleException (Throwable ex) {if(ex = =NULL)            return false; Try {            //use Toast to display exception information            NewThread () {@Override Public voidrun () {looper.prepare (); Toast.maketext (Mcontext,"Sorry, the program is abnormal and is about to restart.", Toast.length_long). Show ();                Looper.loop ();            }}.start (); //collecting device parameter informationCollectdeviceinfo (Mcontext); //Save log fileSavecrashinfofile (ex); Systemclock.sleep (3000); } Catch(Exception e) {e.printstacktrace (); }        return true; }    /*** Collect device parameter information * *@paramCTX*/     Public voidCollectdeviceinfo (Context ctx) {Try{packagemanager pm=Ctx.getpackagemanager (); PackageInfo Pi=Pm.getpackageinfo (Ctx.getpackagename (), packagemanager.get_activities); if(Pi! =NULL) {String versionname= Pi.versionname + ""; String Versioncode= Pi.versioncode + ""; Errinfo.put ("Versionname", Versionname); Errinfo.put ("Versioncode", Versioncode); }        } Catch(packagemanager.namenotfoundexception e) {log.e (TAG,"An error occur when collect package info", E); } field[] fields= Build.class. Getdeclaredfields ();  for(Field field:fields) {Try{field.setaccessible (true); Errinfo.put (Field.getname (), Field.get (NULL). toString ()); } Catch(Exception e) {log.e (TAG,"An error occur when collect crash info", E); }        }    }    /*** Save the error message to the file * *@paramex *@returnreturns the file name for easy transfer of files to the server *@throwsException*/    PrivateString Savecrashinfofile (Throwable ex)throwsException {stringbuffer sb=NewStringBuffer (); Try{SimpleDateFormat Sdateformat=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String Date= Sdateformat.format (Newjava.util.Date ()); Sb.append ("\ r \ n" + date + "\ n");  for(Map.entry<string, string>Entry:errInfo.entrySet ()) {String key=Entry.getkey (); String value=Entry.getvalue (); Sb.append (Key+ "=" + value + "\ n"); } writer writer=NewStringWriter (); PrintWriter PrintWriter=NewPrintWriter (writer);            Ex.printstacktrace (PrintWriter); Throwable cause=Ex.getcause ();  while(Cause! =NULL) {cause.printstacktrace (printwriter); Cause=Cause.getcause ();            } printwriter.flush ();            Printwriter.close (); String result=writer.tostring ();            Sb.append (result); String FileName=WriteFile (sb.tostring ()); returnFileName; } Catch(Exception e) {log.e (TAG,"An error occur while writing file ...", E); Sb.append ("An error occur while writing file...\r\n");        WriteFile (Sb.tostring ()); }        return NULL; }    PrivateString WriteFile (String sb)throwsException {String time= Formatter.format (NewDate ()); String FileName= "crash-" + Time + ". Log"; String Path=Getglobalpath (); File dir=NewFile (path); if(!dir.exists ())        {Dir.mkdirs (); } FileOutputStream Fos=NewFileOutputStream (path + fileName,true);        Fos.write (Sb.getbytes ());        Fos.flush ();        Fos.close (); returnFileName; }     Public StaticString Getglobalpath () {returnenvironment.getexternalstoragedirectory (). GetAbsolutePath ()+ file.separator + "Crash" +File.separator; }     Public Static voidSettag (String tag) {tag=tag; }    /*** File Deletion * *@paramautoclearday File Save days*/     Public voidAutoclear (Final intautoclearday) {//Fileutil.delete (Getglobalpath (), new FilenameFilter () {////@Override//Public Boolean Accept (file file, String filename) {//String s = fileutil.getfilenamewithoutextension (filename);//int day = Autoclearday < 0? autoclearday:-1 * autoclearday;//String date = "crash-" + dateutil.getotherday (day);//return Date.compareto (s) >= 0;//            }//        });    }}

Crashhandler for Android

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.