1. 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);}} /** * Custom error handling, collect error messages to send error reports, etc. are done here. * * @param ex * @return true: Returns False if the exception information is processed; */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 message, can be stored 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 has an exception, please record the time and prompt the developer!"); return true;}}