Everyone in the debugging process, often encounter inexplicable program crashes, then how should we look at the details of these crashes?
By Baidu, there are the following methods:
The first is to write two classes
Crashapplication
Package Com.example.endtwo;import android.app.Application; public class Crashapplication extends application { @Override public void OnCreate () { super.oncreate (); Crashhandler Crashhandler = Crashhandler.getinstance (); Crashhandler.init (Getapplicationcontext ()); } }
Crashhandler
Package Com.example.endtwo;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.map;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 the class to take over the program, and record send error report. * * @author User * */public class Crashhandler implements Uncaughtexceptionhandler {public static final String TAG = "Cr Ashhandler ";//system default Uncaughtexception processing class private Thread.uncaughtexceptionhandler mdefaulthandler;// Crashhandler instance private static Crashhandler instance = new Crashhandler ();//Program Context object private context mcontext;//used to store device information and exception information private map<string, string> Infos = 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 ");/** guarantee only one Crashhandler instance */private Crashhandler () {}/** Get Crashhandler instance, Singleton mode */public static Crashhandler getinstance () {return INSTANCE;} /** * Initialize * * @param context */public void init (context context) {Mcontext = context;//get system default Uncaughtexception processor Mdefaul Thandler = Thread.getdefaultuncaughtexceptionhandler ();// Set the Crashhandler as the program's default processor Thread.setdefaultuncaughtexceptionhandler (this);} /** * When uncaughtexception occurs, it is transferred to the function to process */@Overridepublic void uncaughtexception (thread thread, Throwable ex) {if (! HandleException (ex) && Mdefaulthandler! = null) {//If the user does not handle it, let the system default exception handler handle the Mdefaulthandler.uncaughtexception (thread, ex);} else {try {thread.sleep,} catch (Interruptedexception e) {log.e (TAG, "error:", e);} 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 (Throwable ex) {if (ex = = null) {return false;} Use Toast to display exception information new Thread () {@Overridepublic void run () {looper.prepare (); Toast.maketext (Mcontext, "Sorry, the program has an exception and is about to exit.", Toast.length_long). Show (); Looper.loop ();}}. Start ();//Collect equipment parameter information collectdeviceinfo (mcontext);//Save log file Savecrashinfo2file (ex); return true;} /** * Collect device parameter information * @param ctx */public void Collectdeviceinfo (Context ctx) {try {packagemanager pm = Ctx.getpackagemanager () ; 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);}} catch (Namenotfoundexception e) {log.e (TAG, "An error occured if 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 for easy Transfer of file to server */private String Savecrashinfo2file (Throwable ex) {Stringbuffe R sb = new StringBuffer (); for (map.entry<string, string> entry:infos.entrySet ()) {String key = Entry.getkey (); String value = Entry.getvalue (); Sb.append (key + "=" + value + "\ n");} 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 = "/sdcard/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;}}
Because this involves writing to a file, add a permission to the Androidmanifest.xml file:
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
and add the following sentence to the application:
<application android:name= ". Crashapplication "
This way, if the program crashes, you can look for the generated error file under the crash folder.
Android handling of application crashes due to no exception handling