Handling crash flashback errors in Android

Source: Internet
Author: User
Tags dateformat throwable

Handle crash flashback exception in Android

As we all know, now install Android system mobile phone version and devices vary widely, in the emulator running a good program installed on a phone may crash, developers can not buy all the equipment to debug one by one, so after the program released, if there is a crash phenomenon, Developers should be in time to get information on the device that caused the crash, which is very helpful for the next version of bug fix, so let's describe how to collect the relevant device parameter information and specific exception information in case of a program crash, and send this information to the server for the developer to analyze and debug the program.

What we need is that the software has a global exception trap, when there is an exception we did not find, catch the exception, and record the exception information, upload to the server public development This analysis of the specific reasons for the exception. But first of all, let's look at the following two classes: Android.app.Application and Java.lang.Thread.UncaughtExceptionHandler.

Application: Used to manage the global state of an application. When the application starts, application is created first, and then the activity and service are started according to the situation (Intent). In this example, the unhandled exception handler is registered in the application of the custom-enhanced version.

Thread.uncaughtexceptionhandler: The thread did not catch the exception handler to handle the uncaught exception. If the program has an uncaught exception, the dialog box is forced to close on the system by default. We need to implement this interface and register the exception handling as not caught by default in the program. This allows you to do some personalized exception handling when an uncaught exception occurs.

Appexception.java implements the Thread.uncaughtexceptionhandler, which allows us to handle the main members of an uncaught exception, with the following code:

 PackageCn.com.ista.pdachina.app;ImportJava.io.File; ImportJava.io.FileOutputStream; ImportJava.io.PrintWriter; ImportJava.io.StringWriter; ImportJava.io.Writer; ImportJava.lang.Thread.UncaughtExceptionHandler; ImportJava.lang.reflect.Field; ImportJava.text.DateFormat; ImportJava.text.SimpleDateFormat; Importjava.util.Date; ImportJava.util.HashMap; ImportJava.util.Map; ImportAndroid.content.Context; ImportAndroid.content.pm.PackageInfo; ImportAndroid.content.pm.PackageManager; Importandroid.content.pm.PackageManager.NameNotFoundException; ImportAndroid.os.Build; Importandroid.os.Environment; ImportAndroid.os.Looper; ImportAndroid.util.Log; ImportAndroid.widget.Toast; /*** Appexception processing class, when the program occurs uncaught exception, there is this class to take over the program, and record send error report. *   * @authorUser **/   Public classAppexceptionImplementsUncaughtexceptionhandler { Public Static FinalString TAG = "Appexception"; //system default Uncaughtexception processing class    PrivateThread.uncaughtexceptionhandler Mdefaulthandler; //Crashhandler Instances    Private StaticAppexception INSTANCE =Newappexception (); //context object for the program    PrivateContext Mcontext; //used to store device information and exception information    Privatemap<string, string> infos =NewHashmap<string, string>(); //used to format the date as part of the log file name    PrivateDateFormat formatter =NewSimpleDateFormat ("Yyyy-mm-dd-hh-mm-ss"); /**guaranteed only one appeeception instance*/      Privateappexception () {}/**get appexception instances, Singleton mode*/       Public Staticappexception 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); }        /*** 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 {              Try{Thread.Sleep (3000); } Catch(interruptedexception e) {log.e (TAG,"Error:", E); }              //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; }          //use Toast to display exception information        NewThread () {@Override Public voidrun () {looper.prepare (); Toast.maketext (Mcontext,"Sorry, the program is out of the ordinary and is about to exit.", Toast.length_long). Show ();              Looper.loop ();          }}.start (); //collecting device parameter informationCollectdeviceinfo (Mcontext); //Save log fileSavecrashinfo2file (ex); 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 = =NULL? "NULL": Pi.versionname; String Versioncode= Pi.versioncode + ""; Infos.put ("Versionname", Versionname); Infos.put ("Versioncode", Versioncode); }          } Catch(namenotfoundexception e) {log.e (TAG,"An error occured when collect package info", E); } field[] fields= Build.class. Getdeclaredfields ();  for(Field field:fields) {Try{field.setaccessible (true); Infos.put (Field.getname (), Field.get (NULL). toString ()); LOG.D (TAG, Field.getname ()+ ":" + field.get (NULL)); } Catch(Exception e) {log.e (TAG,"An error occured 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*/      PrivateString Savecrashinfo2file (Throwable ex) {StringBuffer SB=NewStringBuffer ();  for(Map.entry<string, string>Entry:infos.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.close (); String result=writer.tostring ();          Sb.append (result); Try {              Longtimestamp =System.currenttimemillis (); String Time= Formatter.format (NewDate ()); String FileName= "log-" + Time + "-" + timestamp + ". Log"; if(Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {String path= Android.os.Environment.getExternalStorageDirectory (). GetAbsolutePath () + "/pdachina/"; File dir=NewFile (path); if(!dir.exists ())                  {Dir.mkdirs (); } FileOutputStream Fos=NewFileOutputStream (path +fileName);                  Fos.write (Sb.tostring (). GetBytes ());              Fos.close (); }              returnFileName; } Catch(Exception e) {log.e (TAG,"An error occured while writing file ...", E); }          return NULL; }  }  

After this appexception is completed, we need to run it in a application environment, for which we inherit android.app.Application, add our own code, Appcontext.java code as follows:

 PackageCn.com.ista.pdachina.app;Importandroid.app.Application;ImportAndroid.content.Context;/*** Global Get Context class: For saving and invoking global app configuration and accessing network data *@authorGuopeng *@version1.0 * @created 2015-10-26*/ Public classAppContextextendsApplication {Private StaticContext instance; @Override Public voidOnCreate () {instance=Getapplicationcontext (); Appexception appexception=appexception.getinstance ();    Appexception.init (instance); }         Public StaticContext GetContext () {returninstance; }    }

Finally, in order for our appcontext to take the place of android.app.Application in our code, we need to modify the Androidmanifest.xml:

<application android:name= ". Crashapplication "...>  </application>  

Because of our above appexception, after encountering an exception to save the device parameters and specific exception information to SDcard, so we need to add read and write SDcard permissions in Androidmanifest.xml:

<!---<android:name= "Android.permission.WRITE_ External_storage "/><android:name=" Android.permission.MOUNT_UNMOUNT_FILESYSTEMS "/>

Done

Handling crash flashback errors in 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.