Capture android program crash logs

Source: Internet
Author: User

Capture android program crash logs

Main categories:

 

Package com. example. callstatus; import java. io. file; import java. io. fileOutputStream; import java. io. printWriter; import java. io. stringWriter; import java. lang. thread. uncaughtExceptionHandler; import java. lang. reflect. field; import java.net. unknownHostException; import java. text. dateFormat; import java. text. simpleDateFormat; import java. util. date; import java. util. hashMap; import java. util. map; import android. annotation. suppressLint; 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. logoff; import android. telephony. telephonyManager; import android. text. textUtils; import android. util. log; import android. widget. toast;/*** capture android program crash logs * UncaughtException processing class. When the program encounters an Uncaught exception, this class is used to take over the program. ** @ author PMTOAM **/@ SuppressLint (SimpleDateFormat) public class CrashHandler implements UncaughtExceptionHandler {public static final String TAG = CrashHandler. class. getCanonicalName (); // 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
 
  
Infos = new HashMap
  
   
(); // Used to format the date. As part of the log file name, private DateFormat formatter = new SimpleDateFormat (yyyyMMdd_HHmmss);/*** ensure that there is only one instance */private CrashHandler () {}/*** get 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. getDefaultUncaughtExceptionHandler (); // set the CrashHa Ndler is the default processor Thread of the program. setDefaultUncaughtExceptionHandler (this);}/*** when UncaughtException occurs, it will be transferred to this function for processing */@ 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;} // use Toast to display the exception information new Thread () {@ Overridepublic void run () {loid. prepare (); Toast. makeText (mContext, sorry, the program encountered an exception ., Toast. LENGTH_LONG ). show (); logoff. loop ();}}. start (); // collect the device parameter information collectDeviceInfo (mContext); // Save the Log file String str = saveCrashInfo2File (ex); Log. e (TAG, str); return false;}/*** 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, transfers files to the server */private String saveCrashInfo2File (Throwable ex) {StringBuffer sb = new StringBuffer (); for (Map. entry
   
    
Entry: infos. entrySet () {String key = entry. getKey (); String value = entry. getValue (); sb. append ([+ key +, + value +]);} sb. append (+ getStackTraceString (ex); try {String time = formatter. format (new Date (); TelephonyManager mTelephonyMgr = (TelephonyManager) mContext. getSystemService (Context. TELEPHONY_SERVICE); String imei = mTelephonyMgr. getDeviceId (); if (TextUtils. isEmpty (imei) {imei = unknownimei ;} String fileName = CRS _ + time + _ + imei +. txt; File sdDir = null; if (Environment. getExternalStorageState (). equals (android. OS. environment. MEDIA_MOUNTED) sdDir = Environment. getExternalStorageDirectory (); File cacheDir = new File (sdDir + File. separator + dPhoneLog); if (! CacheDir. exists () cacheDir. mkdir (); File filePath = new File (cacheDir + File. separator + fileName); FileOutputStream fos = new FileOutputStream (filePath); fos. write (sb. toString (). getBytes (); fos. close (); return fileName;} catch (Exception e) {Log. e (TAG, an error occured while writing file ..., e);} return null;}/*** get the caught exception String */public static String getStackTraceString (Throwable tr) {if (tr = null) {retu Rn;} Throwable t = tr; while (t! = Null) {if (t instanceof UnknownHostException) {return;} t = t. getCause ();} StringWriter sw = new StringWriter (); PrintWriter pw = new PrintWriter (sw); tr. printStackTrace (pw); return sw. toString ();}}
   
  
 


 

Usage:

 

 

package com.example.callstatus;import android.app.Application;public class MyApplication extends Application{@Overridepublic void onCreate(){super.onCreate();CrashHandler crashHandler = CrashHandler.getInstance();crashHandler.init(getApplicationContext());}}

 

 

 

 
  
   
  
 


 

 

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.