1. Brief introduction
An uncaught exception that is thrown by the program can cause the program to exit unexpectedly, the interface is unfriendly, and a critical error message should be logged to the server.
The main use of Uncaughtexceptionhandler here
2. Code implementation
public class Crashhandler implements Uncaughtexceptionhandler {public static final String TAG = Copyofcrashhandler.class. Getsimplename ();//system default Uncaughtexception processing class private Thread.uncaughtexceptionhandler mdefaulthandler;private static Copyofcrashhandler instance;private Context mcontext;private copyofcrashhandler () {}/** Get Crashhandler instance, Singleton mode */ public static Copyofcrashhandler getinstance () {if (instance = = null) instance = new Copyofcrashhandler (); return instance; }/** * Initialize */public void init (context context) {Mcontext = context;//record the default Uncaughtexceptionhandlermdefaulthandler = Thre Ad.getdefaultuncaughtexceptionhandler ();//thread.setdefaultuncaughtexceptionhandler (this);} /** * When uncaughtexception occurs, it is transferred to the function to process */@Overridepublic void uncaughtexception (thread thread, Throwable ex) {if (! HandleException (thread, ex) && Mdefaulthandler! = null) {// Let the system default exception handler handle mdefaulthandler.uncaughtexception (thread, ex) if the user does not handle it;} else {try {thread.sleep (+);} catch (Interruptedexception e) {e.Printstacktrace ();} Android.os.Process.killProcess (Android.os.Process.myPid ()); System.exit (1);}} /** * self-defined error handling, collect error messages to send error reports and other operations are complete here. * * @param ex * @return true: It is assumed that the exception information was processed; otherwise, false is returned. */private boolean handleexception (thread thread, Throwable ex) {if (ex = = null) {return false;} StringBuffer sb = new StringBuffer () sb.append (thread + ", cause by:" + ex). Append ("\r\n\r\n"); stacktraceelement[] elements = Ex.getstacktrace (); for (int i = 0; i < elements.length; i++) {Sb.append (elements[i].tost Ring () + "\ r \ n"); Record key error messages, can be saved locally and uploaded to Server//logutil.bug (TAG, sb.tostring ());//Open new Activity friendly interface prompt//util.showdialog (mcontext, "time : "+util.formatsimpledateandtime (New Date ())," The program is abnormal, please record the time and prompt the developer! "); return true;}}
ANDROID_ Program unhandled exception capture and processing