Android application Crash automatically captures logs _ automatically saves Crash logs to the local device, androidcrash

Source: Internet
Author: User

Android application Crash automatically captures logs _ automatically saves Crash logs to the local device, androidcrash

After the application crash occurs, you need to view the log to identify the problem. However, once the application is released, you need to find a way to analyze the user's crash log.

Therefore, we need to capture logs after the crash occurs and upload them to the server for developers to check. Now there are many third parties doing this service. Here we will explain how to implement it on our own.

In fact, the principle is very simple. When an application encounters an exception, the default exception processor will handle the exception,

All we need to do is take over the task and handle exceptions by ourselves, including collecting logs, saving them locally, and then uploading them to the server.

The following are self-implemented exception handling classes.

Public class CrashHandler implements UncaughtExceptionHandler {public static final String TAG = "CrashHandler"; // The default UncaughtException class private Thread. uncaughtExceptionHandler mDefaultHandler; // CrashHandler INSTANCE private static CrashHandler INSTANCE = new CrashHandler (); // The Context object private Context mContext of the program; // private Map used to store device information and exception information <String, String> infos = new HashMap <String, String> (); // used to format the day Private DateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd_HH-mm-ss"); private String nameString;/** ensure only one CrashHandler instance */private CrashHandler () {}/** get the CrashHandler INSTANCE, Singleton mode */public static CrashHandler getInstance () {return INSTANCE ;} /*** initialize ** @ param context */public void init (Context context) {mContext = context; // obtain the default UncaughtException processor mDefaultHandler = Thread. getDef AultUncaughtExceptionHandler (); // sets the CrashHandler as the default processor Thread of the program. setDefaultUncaughtExceptionHandler (this); nameString = BmobUserManager. getInstance (mContext ). getCurrentUserName ();}/*** when UncaughtException occurs, it is transferred to this function to process */@ Overridepublic void uncaughtException (Thread thread, Throwable ex) {if (! HandleException (ex) & mDefaultHandler! = Null) {// if the user does not process the mDefaultHandler, the system's default exception processor is used to process the mDefaultHandler. uncaughtException (thread, ex);} else {try {Thread. sleep (3000);} catch (InterruptedException e) {Log. e (TAG, "error:", e) ;}// exit the android program. OS. process. killProcess (android. OS. process. myPid (); System. exit (1) ;}/ *** custom error handling, collecting error information, and sending error reports are all completed here. ** @ param ex * @ return true: If the exception information is processed, false is returned. */private boolean handleException (Throwable ex) {if (ex = Null) {return false;} WonderMapApplication. getInstance (). getSpUtil (). setCrashLog (true); // each time the application is checked and there is a log, upload it // use Toast to display the exception information new Thread () {@ Overridepublic void run () {Looper. prepare (); Toast. makeText (mContext, "Sorry, the program encountered an exception. It is collecting logs and is about to exit.", Toast. LENGTH_LONG ). show (); logoff. loop ();}}. start (); // collect device parameter information collectDeviceInfo (mContext); // Save the log file String fileName = 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 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 the error message to the file ** @ param ex * @ return returns the file name, which is convenient for transferring the file to the server */private String saveCrashInfo2File (Throwable ex) {StringBuffer sb = new StringBuffer (); for (Map. entry <String, String> entry: infos. entrySet () {String key = entry. getKey (); String value = entry. getValu E (); 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 (); L. d (WModel. crashUpload, result); sb. append (result); try {long timestamp = System. currentTimeMillis (); String time = formatter. format (new Date (); String fileName = nameString + "-" + time + "-" + timestamp + ". log "; if (Environment. getExternalStorageState (). equals (Environment. MEDIA _ MOUNTED) {String path = WMapConstants. CrashLogDir; 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 ;}}

The usage is as follows:

Add upper and lower planes in onCreate of Application

CrashHandler crashHandler = CrashHandler.getInstance();crashHandler.init(this);

In this way, the application crash automatically saves the log to the local device.

In fact, there is another benefit, that is, you don't need to flip through the logcat to find the log, just go to the local folder to open it.


Author: jason0539

Blog: http://blog.csdn.net/jason0539 (reprinted please explain the source)

Scan the QR code to follow my public account



Related Article

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.