Capture android program crash logs and android logs

Source: Internet
Author: User

Capture android program crash logs and android 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. a Nnotation. 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 the android program crash log <br> * UncaughtException processing class. This class is used to take over the program when an Uncaught exception occurs. ** @ 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 INSTA NCE = new CrashHandler (); // The Context object of the program private Context mContext; // private Map used to store device information and exception information <String, String> infos = new HashMap <String, string> (); // used to format the date. As part of the log file name, private DateFormat formatter = new SimpleDateFormat ("yyyyMMdd_HHmmss "); /*** ensure that only one INSTANCE */private CrashHandler () {}/ *** is used to obtain the 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 (); // sets the CrashHandler as 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, 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. getValue (); sb. a Ppend ("[" + key + "," + value + "] \ n");} sb. append ("\ n" + 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) {re Turn "";} 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());}}


Required permissions:


<uses-permission android:name="android.permission.READ_PHONE_STATE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />



How can I view the logs generated when an error is reported by the android program?

If the program is forced to close, the system will keep the error log, but you need to root to see it. You can also run the debug tool: ddms. bat that comes with the sdk to view the log.
If you are a developer, there is logcat in eclipse to view logs.

How can I get the crash log when the program crashes?

Connect the Device to your computer. On the xcode menu bar, choose window> organizer> Devices> Device Logs.
 

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.