A: Why should we deal with it?
In fact, we all know that in the development process, their own app system may have a lot of hidden anomalies, they did not capture, then about the exception of the capture, which is quite important, if the system crashes, then at least can let the system hangs within the system, will not find what system directly back, or is stuck, so do, Can make the user experience more effective, they can also find out what the user in the end what is abnormal, to facilitate their own later to deal with this problem, optimize the processing of their own system.
Second: How to Solve
In Android development, itself with a system default exception processing interface, Uncaughtexceptionhandler, this interface, can be very good to deal with the exception in the program, so, often developers like to use it, and it is also a very simple and useful things.
Three: Concrete Implementation
(1) class to implement the Uncaughtexceptionhandler interface
Package Com.x1.tools;import Java.lang.thread.uncaughtexceptionhandler;import Android.app.activitymanager;import Android.content.componentname;import Android.content.context;import Android.os.looper;import Android.util.Log; Import Com.x1.dao.submitconfigbugs;import com.x1.ui.r;/** * uncaught Exception Capture class * * @author Zengtao May 6, 2015 * * */public class Cra Shhandlers implements Uncaughtexceptionhandler {public static final String TGA = "crashhandlers";// system default Uncaughtexception Processing class private Thread.uncaughtexceptionhandler mdefaulthandler;//Crashhandler instance private static Crashhandlers instance;//program's context object private context Mcontext;private Getphoneinfo phone;/** guaranteed only one Crashhandler instance */ Private Crashhandlers () {}/** gets Crashhandler instance, singleton mode */public synchronized static crashhandlers getinstance () {if (Instan CE = = null) {instance = new Crashhandlers ();} return instance;} /** * Initialize * * @param context */public void init (context context) {Mcontext = context;//get system default Uncaughtexception processor Mdefau Lthandler = thread.geTdefaultuncaughtexceptionhandler ();//Set the Crashhandler as the program's default processor Thread.setdefaultuncaughtexceptionhandler (this); Phone = new Getphoneinfo (context);} /** * 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) {log.e (TGA, e.tostring ());} Exit Program 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;} Use Toast to display exception information new Thread () {@Overridepublic void run () {looper.prepare (); Showtoast.show (Mcontext, "Meow, I'm sorry, the program is abnormal, is about to exit!", R.drawable.error_icon); Looper.loop ();}}. Start ();//upload exception information and device information to server Submitthreadanddeviceinfo (Mcontext, Thread, ex); return TRUE;} Submit information to server public void Submitthreadanddeviceinfo (Context ctx, Thread thread,throwable ex) {//Current user's account string = null ; if (Config.getcachedaccount (CTX) = null) {account = Config.getcachedaccount (CTX);} else {client = "No user currently logged in";} Information about the mobile device string Phonemodel = phone. Phonemodel; String phoneversion = phone. Phoneversion; String phoneresolution = phone. Phoneresolution; String zcmversion = phone. Zcmversion; String Availablerom = phone. availablerom;//gets the path of the activity currently displayed on the interface plus the class name Activitymanager am = (activitymanager) ctx.getsystemservice ( Context.activity_service); ComponentName cn = Am.getrunningtasks (1). Get (0). topactivity;//exception information plus an absolute path to the class where the exception is located final String content = "Thread:" + thread + ", Name:" + thread.getname () + ", ID:" + thread.getid () + ", exception:" + ex + "," + cn.getclassname ();//execute interface, lift exception information Submit to server new Submitconfigbugs (0, CTX, account, Phonemodel, Phoneversion,phoneresolution, Zcmversion, Availablerom, content , new Submitconfigbugs.successcallback () {@Overridepublic void onsuccess () {LOG.E (TGA, content + "\ n error message submitted successfully")}, new Submitconfigbugs.failcallback () {@Overridepublic void Onfail () {LOG.E (TGA, C Ontent + "\ n Error message submission failed"}});}}
(2) Entity class: Mobile Information
Package Com.x1.tools;import Android.content.context;import Android.content.pm.packageinfo;import Android.content.pm.packagemanager;import Android.os.environment;import Android.os.statfs;import Android.text.textutils;import Android.view.display;import android.view.windowmanager;/** * Get current phone device information and version of current software * * @ Author Zengtao May 6, 2015 * * */public class Getphoneinfo {private Context context;public string Phonemodel;public string P Honeversion;public string Phoneresolution;public string Zcmversion;public string Availablerom;public GetPhoneInfo ( Context context) {This.context = context; Phonemodel = Android.os.Build.MODEL; Phoneversion = Android.os.Build.VERSION.RELEASE; Phoneresolution = Getdisplaywandh (); Zcmversion = Getappversionname (This.context); Availablerom = "ROM remaining storage space:" + getavailableinternalmemorysize () + "MB" + ", built-in sdcard remaining storage space:" + Getavailableexternalmemorys Ize () + "MB";} Gets the current version number of the private String getappversionname (context context) {String versionname = ""; try {Packagemanager PackagemAnager = Context.getpackagemanager (); PackageInfo PackageInfo = Packagemanager.getpackageinfo ("Com.x1.ui", 0); versionname = Packageinfo.versionname;if ( Textutils.isempty (Versionname)) {return "";}} catch (Exception e) {e.printstacktrace ();} return versionname;} Get screen resolution @suppresswarnings ("deprecation") private String Getdisplaywandh () {WindowManager wm = (WindowManager) Context.getsystemservice (context.window_service);D isplay Display = Wm.getdefaultdisplay (); String string = "screen Resolution:" + display.getwidth () + "X" + display.getheight (); return string;} /** * * @return ROM storage path */private String Getinternalmemorypath () {return environment.getdatadirectory (). GetPath (); /** * * @return built-in SD card path */private String Getexternalmemorypath () {return environment.getexternalstoragedirectory (). GetPath ();} /** * * @param path * File path * @return file path Statfs Object * @throws Exception * path is empty or illegal exception thrown */private Sta TFs getstatfs (String path) {try {return new StatFs (path)} catch (Exception e) {E.prinTstacktrace ();} return null;} /** * * @param stat * File statfs Object * @return MB of remaining storage space * */@SuppressWarnings ("deprecation") private float CALCU LATESIZEINMB (StatFs stat) {if (stat! = null) return Stat.getavailableblocks () * (Stat.getblocksize ()/(1024f * 1024f)); RET Urn 0.0f;} /** * * @return MB of remaining storage space */private float getavailableinternalmemorysize () {String path = Getinternalmemorypath ();// Get Data directory Statfs stat = getstatfs (path); return CALCULATESIZEINMB (stat);} /** * * @return built-in sdcard remaining MB of storage */private float getavailableexternalmemorysize () {String path = Getexternalmemorypath () ;//Get Data directory Statfs stat = getstatfs (path); return CALCULATESIZEINMB (STAT);}}
Four: summary
Above, you can directly catch the unhandled exception in the program, and make the user in the system's own development crash, do not cause, directly hung, so, in the program, do such processing is very necessary, in the above Crashhandlers has an execution interface processing, Submit data to the server, this is the interface defined in its own development, this can be implemented according to their own ideas, I in this, is the mobile phone submitted some information, and error messages sent to the server, and completed, so that they can let themselves know, is what the phone error, have the purpose to deal with, better maintain their own system.
Android captures unhandled exceptions in the app system