Android Crash Exception Capture method _android

Source: Internet
Author: User
Tags dateformat error handling locale throwable stringbuffer

One of the most troubling developments is the application that suddenly explodes and then jumps back to the desktop. And we often do not know when this situation will appear, in the application debugging phase is fine, but also through the Debug tool log to see where the error occurred. But when used to give you a crash, then you want to cry no tears.
So today, I'm going to talk about how to capture the unchecked anomalies that appear in the system. What is a unchecked exception, in other words, is a non-inspected exception, it cannot use Try-catch to display capture.

Let's start with the exception. Exception are divided into two categories: one is checkedexception, the other is uncheckedexception. The difference between these two kinds of exception is mainly checkedexception need to use try...catch ... The capture that is displayed, and uncheckedexception does not need to be captured. Usually uncheckedexception is also called RuntimeException. "Effective Java" states that using a checked exception (checkedexception) for a recoverable condition uses a Run-time exception (runtimeexception) for program errors (which cannot be recovered by implication). 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. IOException in IO packages and their subclasses, these are checkedexception.

First, use Uncaughtexceptionhandler to catch unchecked exceptions

Uncaughtexception processing class, when the program occurs uncaught exception, by the class to take over the program, and record the sending error report.
Just go to the code.

Import Java.io.File;
Import Java.io.FileOutputStream;
Import Java.io.PrintWriter;
Import Java.io.StringWriter;
Import Java.io.Writer;
Import Java.lang.Thread.UncaughtExceptionHandler;
Import Java.lang.reflect.Field;
Import Java.text.DateFormat;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
Import Java.util.HashMap;
Import Java.util.Locale;
Import Java.util.Map;
Import Java.util.Map.Entry;
Import Java.util.regex.Matcher;
Import Java.util.regex.Pattern;
Import Android.annotation.SuppressLint;
Import Android.content.Context;
Import Android.content.pm.PackageInfo;
Import Android.content.pm.PackageManager;
Import android.content.pm.PackageManager.NameNotFoundException;
Import Android.os.Build;
Import android.os.Environment;
Import Android.os.Looper;
Import Android.util.Log;
Import Android.widget.Toast;
/** * Uncaughtexception processing class, when the program occurs uncaught exception, there is a class to take over the program, and record the sending error report. * * @author User * */@SuppressLint ("Sdcardpath") public class Crashhandler implements UncaughtexceptionhandleR {public static final String TAG = ' TEST ';//Crashhandler Instance private static Crashhandler INSTANCE = new Crashhandler ();
The context object of the program is private context Mcontext;
system default Uncaughtexception Processing class private Thread.uncaughtexceptionhandler mdefaulthandler;
Used to store device information and exception information private map<string, string> infos = new hashmap<string, string> ();
Used to display information in toast private static String error = "program error, amount, no, I should say, the server is in maintenance, please try again later";
Private static final map<string, string> regexmap = new hashmap<string, string> ();
Used to format the date as part of the log file name private DateFormat formatter = new SimpleDateFormat ("Yyyy-mm-dd-hh-mm-ss", Locale.china); /** guarantee Only one Crashhandler instance/private Crashhandler () {//}/** get Crashhandler instance, Singleton mode */public static Crashhandler gets  Instance () {initmap (); return Instance}/** * Initialization * * @param context */public void init (context) {Mcontext =
Context
Gets the system default Uncaughtexception processor Mdefaulthandler = Thread.getdefaultuncaughtexceptionhandler (); Set the CRAsHhandler is the default processor for the program Thread.setdefaultuncaughtexceptionhandler (this);
LOG.D ("TEST", "Crash:init"); /** * When uncaughtexception occurs, it is transferred to the function to process/@Override public void uncaughtexception (thread thread, Throwable ex) {if (!ha Ndleexception (ex) && mdefaulthandler!= null) {//If the user does not have a deal, let the system default exception handler handle the Mdefaulthandler.uncaughtexception (
Thread, ex);
LOG.D ("TEST", "Defalut");
else {try {thread.sleep ();} catch (Interruptedexception e) {log.e (TAG, "error:", e);}
Exit Program Android.os.Process.killProcess (Android.os.Process.myPid ());
Mdefaulthandler.uncaughtexception (thread, ex);
System.exit (); }/** * Custom error handling, collect error messages, send error reports, and so on are done here * * @param ex * @return true: If the exception information is processed, otherwise return false/private Boolean HANDLEEXCEP tion (Throwable ex) {if (ex = null) {return false;}//Collect device parameter information//Collectdeviceinfo (Mcontext);//save log file Savecrashinfo
File (ex);
Use Toast to display exception information new Thread () {@Override public void run () {looper.prepare ();
Toast.maketext (Mcontext, Error, Toast.length_long). Show (); LOoper.loop ();
}}.start ();
return true; /** * Collect device parameter information * * @param CTX/public void Collectdeviceinfo (context ctx) {try {packagemanager pm = Ctx.getpackagem
Anager ();
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);
The 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 error message to File * * * @param ex * @return return file name to facilitate transfer of file to server/private String savecrashinfofile (Throwable ex) {STringbuffer SB = Gettraceinfo (ex);
Writer Writer = new StringWriter ();
PrintWriter printwriter = new PrintWriter (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 {long timestamp = System.currenttimemillis ();
String time = Formatter.format (new Date ());
String fileName = "crash-" + Time + "-" + timestamp + ". Log"; if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {String Path =
Environment.getexternalstoragedirectory () + "/crash/";
File dir = new file (path);
if (!dir.exists ()) {dir.mkdirs ();}
FileOutputStream fos = new FileOutputStream (path + fileName);
Fos.write (Sb.tostring (). GetBytes ());
Fos.close ();
return fileName;
catch (Exception e) {log.e (TAG, "An error occured while writing file ...", e);}
return null; /** * Collation Exception information * @param e * @return/public static StringBuffer Gettraceinfo (Throwable e) {stringbuffer sb = new StringBuffer (); Throwable ex = e.getcause () = null?
E:e.getcause ();
Stacktraceelement[] Stacks = Ex.getstacktrace (); for (int i =; i < stacks.length; i++) {if (i = =) {SetError (ex.tostring ()), Sb.append ("Class:"). Append (Stacks[i). GetClassName ()). Append ("; Method: "). Append (Stacks[i].getmethodname ()). Append ("; Line: "). Append (Stacks[i].getlinenumber ()). Append (";
Exception: "). Append (ex.tostring () +" \ n ");
LOG.D (TAG, sb.tostring ());
return SB;
/** * Set the wrong prompt * @param e */public static void SetError (String e) {pattern pattern;
Matcher Matcher; For (entry<string, string> m:regexmap.entryset ()) {LOG.D (TAG, e+ "key:" + m.getkey () +;
Value: "+ m.getvalue ());
Pattern = Pattern.compile (M.getkey ());
Matcher = Pattern.matcher (e);
if (Matcher.matches ()) {error = M.getvalue (); break;}} /** * Initialization error prompt */private static void Initmap () {//Java.lang.NullPointerException//Java.lang.ClassNotFoundExceptIon//Java.lang.ArithmeticException//java.lang.ArrayIndexOutOfBoundsException// Java.lang.IllegalArgumentException//java.lang.IllegalAccessException//secturityexception// NumberFormatException//OutOfMemoryError//Stackoverflowerror//RuntimeException Regexmap.put (". *
Nullpointerexception.* "," Hey, nothing ~boom! "); Regexmap.put (". *classnotfoundexception.*"), "Are you sure you can find it?"
"); Regexmap.put (". *arithmeticexception.*", "I guess your maths is taught by the P.E. teacher, right?")
");
Regexmap.put (". *arrayindexoutofboundsexception.*", "en, no lower bound = no moral integrity, please do not talk to me"); Regexmap.put (". *illegalargumentexception.*"), "Your birth is a mistake."
");
Regexmap.put (". *illegalaccessexception.*", "Unfortunately, your credit card account has been frozen, no right to pay");
Regexmap.put ("*secturityexception.*", "Death Comes Soon"); Regexmap.put (". *numberformatexception.*"), "want to change your image?"
Go to Thailand, package you Satisfied ");
Regexmap.put (". *outofmemoryerror.*", "Maybe you should lose weight"); Regexmap.put (". *stackoverflowerror.*", "Ah, ah, can't hold out!")
");
Regexmap.put ("*runtimeexception.*", "Your life is going in the wrong direction, come Again"); }
}

Second, the establishment of 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 to the configuration file

 
 

and Permissions

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

Commit error log to network server this piece has not been added yet. If you add this piece of functionality, you will be able to real-time users of the error log, to be able to timely feedback of different models at different times of the error, can be the late maintenance of our developers to bring great convenience.

On the Android crash exception capture method small series to introduce so many people, I hope to help you!

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.