Capture Android Program crash log

Source: Internet
Author: User
Tags dateformat

Main classes:

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.looper;import Android.telephony.telephonymanager;import Android.text.textutils;import Android.util.log;import android.widget.toast;/** * Capture Android Program crash log <br> * Uncaughtexception processing class, This class takes over the program when a uncaught exception occurs. * * @author PMTOAM * * */@SuppressLint ("SimpleDateFormat") public class Crashhandler implements UncaughtexceptionhandLer{public static final String TAG = CrashHandler.class.getCanonicalName ();//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 ("Yyyymmdd_ Hhmmss ");/** * Guaranteed only one instance */private Crashhandler () {}/** * Get instance, Singleton mode */public static Crashhandler getinstance () {return INSTA NCE;} /** * 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) {Let the system default exception handler handle mdefaulthandler.uncaughtexception (thread, ex) if the user does not handle it;} Else{try{thread.sleep (3000);} 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.) ", Toast.length_long). Show (); Looper.loop ();}}. Start ();//Collect device parameter information collectdeviceinfo (mcontext);//save 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 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");} 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;} /** * Gets the string that catches the exception */public static string getstacktracestring (Throwable tr) {if (tr = = null) {return "";} 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 ();}} 


How to use:


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 "/>


Capture Android Program crash log

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.