Android captures crash exception

Source: Internet
Author: User
Tags dateformat

One of the biggest headaches in development is the sudden explosion of applications and the jump back to the desktop. And we often do not know when this situation will occur, in the application debugging phase is OK, but also through the Debug tool log to see where the error occurs. But the usual use of the time to give you a crash, then you want to cry without tears.

So today we'll focus on how to capture the unchecked anomalies that occur in the system. What is unchecked exception , in other words, refers to non-inspected exception, it can not use Try-catch to display the capture.

Let's start with the exception. Exception is divided into two categories: one is checkedexception and the other is uncheckedexception. The difference between the two types of exception is mainly checkedexception need to use try...catch ... The capture is displayed, while the uncheckedexception does not need to be captured. Usually uncheckedexception is also called RuntimeException. Effective Java states that using a checked exception (checkedexception) for recoverable conditions uses a run-time exception (RuntimeException) for a program error (the implication is unrecoverable and a blunder has been made). Our common Runtimeexcepiton are illegalargumentexception, IllegalStateException, NullPointerException, Indexoutofboundsexception and so on. For those checkedexception, we are in the process of writing programs try...catch ... The catch exception is checkedexception. The IOException and its subclasses in the IO package are checkedexception.

First, using Uncaughtexceptionhandler to capture unchecked anomalies

Uncaughtexception processing class, when the program occurs uncaught exception, by this class to take over the program, and record send error report.

Go directly to the code.

  1 Import java.io.File;  2 Import Java.io.FileOutputStream;  3 Import Java.io.PrintWriter;  4 Import Java.io.StringWriter;  5 Import Java.io.Writer;  6 Import Java.lang.Thread.UncaughtExceptionHandler;  7 Import Java.lang.reflect.Field;  8 Import Java.text.DateFormat; 9 Import Java.text.SimpleDateFormat; Ten import java.util.Date; Import Java.util.HashMap; Import Java.util.Locale; Import Java.util.Map; Import Java.util.Map.Entry; Java.util.regex.Matcher import; Java.util.regex.Pattern import; Android.annotation.SuppressLint import; Import Android.content.Context; Import Android.content.pm.PackageInfo; Android.content.pm.PackageManager import; Import android.content.pm.PackageManager.NameNotFoundException; Android.os.Build import; Import android.os.Environment; Import Android.os.Looper; Android.util.Log import; Android.widget.Toast import; /** * Uncaughtexception processing class, when the program occurs uncaught exception, there is the class to take over the program, and record send error report. * * @authoR User * * * * * @SuppressLint ("Sdcardpath") $ public class Crashhandler implements Uncaughtexceptionhandler {37 A. public static final String TAG = "TEST"; Max//Crashhandler instance of private static Crashhandler INSTANCE = new Crashhandler (); 42 43//Program Context object to the private context mcontext; 45 46//system default Uncaughtexception processing class Thread.uncaughtexceptionhandler Mdefaulthandler; 48 49//used to store device information and exception information map<string, string> infos = new hashmap<string, string> (); 51 52//used to display information in toast private static String error = "program error, amount, no, I should say, the server is being maintained, please try again later"; Map<string private static final, string> Regexmap = new hashmap<string, string> ();             56 57//For formatted date, as part of the log file name DateFormat formatter = new SimpleDateFormat ("Yyyy-mm-dd-hh-mm-ss", 59 Locale.china); 60 61/** Guaranteed that there is only one Crashhandler instance */+ private Crashhandler () {63//64} 65 66/** Get Crashhandler instance, Singleton mode */"Crashhandler" Static "Initmap" getinstance () Eturn INSTANCE; 70} 71 72/** 73 * Initialize the * * * * @param context * * * Conte public void init (context) XT) {Mcontext = context; 79 80//Get system default Uncaughtexception processor Bayi Mdefaulthandler = THREAD.G Etdefaultuncaughtexceptionhandler (); 82 83//Set the Crashhandler as the program's default processor Thread.setdefaultuncaughtexceptionhandler (this); LOG.D ("TEST", "Crash:init"); 86} 87 88/** 89 * When uncaughtexception occurs, it is transferred to the function to process the * * * @Override, the public void uncaught             Exception (thread thread, Throwable ex) {!handleexception (ex) && Mdefaulthandler! = null) {94 If the user does not process then let the system default exception processor to handle the mdefaulthandler.uncaughtexception (thread, ex); LOG.D ("TEST", "Defalut");           98} else {try {99}      Thread.Sleep (Interruptedexception e) {101 log.e (TAG, "error:", e); 1             02}103//Exit Program 104 android.os.Process.killProcess (Android.os.Process.myPid ()); 105     Mdefaulthandler.uncaughtexception (thread, ex); 106 System.exit (1); 107}108}109 110       /**111 * Custom error handling, collection of error messages, sending error reports and other operations are done here. * 113 * @param ex114 * @return true: If the exception information is processed, otherwise returns false115 */116 Private Boolean handleexception (Throwable ex) {117 if (ex = = null) {118 return false;1 19}120 121//Collect equipment parameter information 122//Collectdeviceinfo (Mcontext); 123//Save log file 124 Savecra Shinfo2file (ex); 125//Use Toast to display exception information 126 new Thread () {127 @Override128 public V OID Run () {129 looper.prepare (); Toast.maketext (Mcontext, Error, Toast.length_long). Sho                 W (); 131Looper.loop ();}133}.start () 134 return true;135}136 137/**138 * collect device parameter information 13             9 * ctx141 * @param */142 public void Collectdeviceinfo (Context ctx) {143 try {144 Packagemanager pm = Ctx.getpackagemanager (); 145 packageinfo pi = pm.getpackageinfo (Ctx.getpackagename (), 14 6 packagemanager.get_activities); 147 148 if (pi! = null) {149 String Versi Onname = Pi.versionname = = null?                 "Null" 150:pi.versionname;151 String Versioncode = Pi.versioncode + ""; 152             Infos.put ("Versionname", versionname); 153 Infos.put ("Versioncode", Versioncode); 154 }155} catch (Namenotfoundexception e) {156 log.e (TAG, "An error occured when collect package info", E ); 157}158 159 field[] fields = Build.class.getDeclaredFields (); (Field field:fIelds) {161 try {162 field.setaccessible (true); 163 infos.put (Field.getname (), Field.get (NULL). ToString ()); 164 log.d (TAG, Field.getname () + ":" + field.get (null)); 165} CA         TCH (Exception e) {166 LOG.E (TAG, "An error occured when collect crash info", e); 167}168 }169}170 171/**172 * Save error message to file *173 * 174 * @param ex175 * @return return file name for easy transfer of files to server 17         6 */177 Private String savecrashinfo2file (Throwable ex) {178 StringBuffer SB = Gettraceinfo (ex); 179 Writer writer = new StringWriter (); PrintWriter printwriter = new PrintWriter (writer); 181 ex.printst Acktrace (printwriter); 182 throwable cause = Ex.getcause (); 183 while (cause! = NULL) {184 cause . Printstacktrace (printwriter); 185 cause = Cause.getcause (); 186}187 Printwriter.close (); 188 18 9 String Result= Writer.tostring (); Sb.append (result); 191 try {192 long timestamp = System.currenttimemill Is (); 193 String time = Formatter.format (new Date ()); 194 string fileName = "crash-" + Time + "-" + Timestamp + ". Log"; 195 196 if (Environment.getexternalstoragestate (). Equals (197 environmen                         t.media_mounted)) {198 String path = environment.getexternalstoragedirectory () 199                     + "/crash/"; file dir = new file (path); 201 if (!dir.exists ()) {202                 Dir.mkdirs (); 203}204 FileOutputStream fos = new FileOutputStream (path + fileName); 205 Fos.write (Sb.tostring (). GetBytes ()); 206 Fos.close (); 207}208 209 Retu          RN filename;210} catch (Exception e) {211 LOG.E (TAG, "An error occured while writing file ...", e); 212       }213 214  Return null;215}216 217/**218 * Sorting exception Information 219 * @param e220 * @return221 */222 public stat  IC StringBuffer gettraceinfo (Throwable e) {223 StringBuffer sb = new StringBuffer (); 224 225 Throwable ex = E.getcause () = = null? E:e.getcause (); 226 stacktraceelement[] stacks = Ex.getstacktrace (); 227 for (int i = 0; i < Stacks.len Gth i++) {228 if (i = = 0) {229 seterror (ex.tostring ());}231 Sb.append ( "Class:"). Append (Stacks[i].getclassname ()) 232. Append ("; Method: "). Append (Stacks[i].getmethodname ()) 233. Append (";  Line: "). Append (Stacks[i].getlinenumber ()) 234. Append (";     Exception: "). Append (ex.tostring () +" \ n "), 235}236 log.d (TAG, sb.tostring ()); 237 return sb;238         }239 240/**241 * Set error prompt 242 * @param e243 */244 public static void SetError (String e) {245Pattern pattern;246 Matcher matcher;247 for (entry<string, string> m:regexmap.entryset ()) {248 LOG.D (TAG, e+ "key:" + m.getkey () + "; Value: "+ m.getvalue ()); 249 pattern = Pattern.compile (M.getkey ()); Matcher = Pattern.matcher (e)             ; 251 if (matcher.matches ()) {252 error = M.getvalue (); 253 break;254  }255}256}257 258/**259 * Initialization error prompt 260 */261 private static void Initmap () {262/// Java.lang.NullPointerException263//java.lang.ClassNotFoundException264//Java.lang.ArithmeticException 265//java.lang.ArrayIndexOutOfBoundsException266//java.lang.IllegalArgumentException267//JAV a.lang.illegalaccessexception268//SecturityException269//NumberFormatException270//Outofmemo       ryerror 271//stackoverflowerror 272//runtimeexception 273  Regexmap.put (". *nullpointerexception.*", "Hey, out of Nothing ~boom!"); 274 Regexmap.put (". *classnotfoundexception.*", "Are you sure you can find it?" 275 Regexmap.put (". *arithmeticexception.*", "I guess your maths is taught by a P.E. teacher, right?") 276 Regexmap.put (". *arrayindexoutofboundsexception.*", "Well, no lower limit = no moral integrity, please don't talk to me"); 277 Regexmap.put (". *illegal argumentexception.*, "Your birth is a mistake." 278 Regexmap.put (". *illegalaccessexception.*", "Unfortunately, your credit card account is frozen, not entitled to pay"); 279 Regexmap.put (". *secturityexc Eption.* "," Death Comes Soon "); 280 regexmap.put (". *numberformatexception.* "," want to change your image? ") Go to Thailand, pack your Satisfaction "), 281 regexmap.put (". *outofmemoryerror.* "," Maybe you should lose weight "); 282 regexmap.put (". *stackoverflowerror.* "); , "Ah, ah, can't hold it!" 283 Regexmap.put (". *runtimeexception.*", "Your life goes in the wrong direction, start again"); 284 285}286 287}

Second, establish a application to monitor the global

Import Android.app.application;public class Crashapplication extends application {    @Override public    Void OnCreate () {        super.oncreate ();        Crashhandler Crashhandler = Crashhandler.getinstance ();        Crashhandler.init (Getapplicationcontext ());}    }

Finally, add the registration information in the configuration file

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

and Permissions

    <!--uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/-->    <uses-permission Android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>

Submit error log to Web server this piece has not been added yet. If you add this piece of functionality, you will be able to get real-time user error logs, timely feedback on different models of different times of the error, can be very convenient for our developers of late maintenance.

Android captures crash exception

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.