Processing crash exception for Android development

Source: Internet
Author: User

As we all know, Android devices are very diverse, it is inevitable that a crash anomaly, this time need to catch what crash anomalies, that is, to capture the information about the crash anomaly, and recorded, so that developers and testers to facilitate the analysis and debugging.

1. First we have to create a class to handle the crash exception, which is named: Crashhandler. The implementation is as follows:

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;ImportJava.util.TimeZone;Importandroid.app.Activity;ImportAndroid.app.AlertDialog;ImportAndroid.content.Context;ImportAndroid.content.DialogInterface;ImportAndroid.content.DialogInterface.OnClickListener;Importandroid.content.Intent;ImportAndroid.content.pm.PackageInfo;ImportAndroid.content.pm.PackageManager;Importandroid.content.pm.PackageManager.NameNotFoundException;ImportAndroid.os.Build;ImportAndroid.os.Looper;ImportAndroid.sax.StartElementListener;ImportAndroid.util.Log;ImportAndroid.widget.Toast;/*** Uncaughtexception processing class, when the program occurs uncaught exception, there is the class to take over the program, and record send error report to the log file. *@authorcaizhiming*/ Public classCrashhandlerImplementsUncaughtexceptionhandler { Public Static FinalString TAG = "Crashhandler"; //system default Uncaughtexception processing class    PrivateThread.uncaughtexceptionhandler Mdefaulthandler; //Crashhandler Instances    Private StaticCrashhandler INSTANCE =NewCrashhandler (); //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    PrivateSimpleDateFormat Formatter; /*** 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); }    /*** 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 {            //Exit Program            Try{Thread.Sleep (300); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace ();            } android.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 (FinalThrowable ex) {        if(ex = =NULL) {            return false; }//Intent Showcrashdlg = new Intent (mcontext,crashactivity.class);//mcontext.startactivity (SHOWCRASHDLG);Ex.printstacktrace (); //use Toast to display exception information//collecting device parameter informationCollectdeviceinfo (Mcontext); //Save log fileSavecrashinfotofile (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 *@returnerror crash information written to log file*/    Private voidSavecrashinfotofile (Throwable ex) {StringBuffer SB=NewStringBuffer (); Sb.append ("==============================crash happened at time:" +commonutils.getcurtime ()+ "==============================\r\n");  for(Map.entry<string, string>Entry:infos.entrySet ()) {String key=Entry.getkey (); String value=Entry.getvalue (); Sb.append (Key+ "=" + value + "\ r \ 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{Logcore.addlog (sb.tostring ()); } Catch(Exception e) {log.e (TAG,"An error occured while writing file ...", E);    } analyse.uplodcrash (Sb.tostring ()); }    /*** Display error message with Dialog * *@paramex *@returndisplaying error messages with Dialog*/    Private voidShowcrashinfodialog (Throwable ex) {StringBuffer SB=NewStringBuffer (); 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 {            //Dlgutils.showdialog (Mcontext, "the program crashed"); //LOGCORE.D (mcontext,sb.tostring ());Alertdialog.builder Builder =NewAlertdialog.builder (Mcontext); Builder.settitle ("The program crashed.");            Builder.setmessage (Sb.tostring ()); Builder.setpositivebutton ("I know,"NewOnclicklistener () {@Override Public voidOnClick (Dialoginterface Dialog,intwhich) {                    //TODO auto-generated Method Stubandroid.os.Process.killProcess (Android.os.Process.myPid ()); System.exit (1); }            });//builder.create (). Show ();}Catch(Exception e) {log.e (TAG,"An error occured while writing file ...", E); }    }}

2. Once this crashhandler is completed, we need to run it in a application environment, We inherit android.app.Application, add our own code, the Crashapplication.java code is as follows:

 Package Com.czm.crash;     Import android.app.Application;      Public class extends Application {      @Override      publicvoid  onCreate () {            Super. OnCreate ();           = crashhandler.getinstance ();          Crashhandler.init (Getapplicationcontext ());      }  }  

3. In addition, finally, in order for the above crashapplication to replace the status of Android.app.Application in our code, we need to modify the Androidmanifest.xml:

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

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.