Android Development Exception information collection program code

Source: Internet
Author: User
Tags dateformat throwable

The global application is created first, and this application is globally universal.

Package Com.demo.utils;import Com.demo.exception.crashhandler;import android.app.application;/** * Global Context, Call Anywhere * @author Administrator * */public class Globalapplication extends application{    private static Globalapplicati on instance;    public static Globalapplication getinstance ()    {        return instance;    }    @Override public    void OnCreate ()    {        super.oncreate ();        instance = this;        Crashhandler Crashhandler = Crashhandler.getinstance ();//This is a singleton class that collects exception information, see below crashhandler.init for specific code        ( Getapplicationcontext ());//Initialize    }}

Note: The above code needs to be registered in the registration manifest file. Some of the listings are as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.demo.test "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk an droid:minsdkversion= "8" android:targetsdkversion= "/>" <!--network and <uses-permission Android:nam E= "Android.permission.INTERNET"/> <!--access SDcard--<uses-permission android:name= "ANDROID.PERMISSION.W Rite_external_storage "/> <uses-permission android:name=" Android.permission.READ_EXTERNAL_STORAGE "/> < !--get the network status your Mac needs--<uses-permission android:name= "Andorid.permission.CHANGE_CONFIGURATION"/> <uses-pe Rmission android:name= "Android.permission.CHANGE_NETWORK_STATE"/> <uses-permission android:name= " Android.permission.CHANGE_WIFI_STATE "/> <uses-permission android:name=" android.permission.ACCESS_WIFI_ State "/> <uses-permission android:name=" Android.permissIon. Access_network_state "/> <application android:name=" Com.demo.utils.GlobalApplication "Android:allow Backup= "true" android:icon= "@drawable/app_icon" android:label= "@string/app_name" Android:theme= "@styl E/apptheme "> <activity android:name=" com.demo.activity.MyActivity "android:launchmode= "Singletask" android:screenorientation= "Landscape" android:theme= "@android: Style/theme.notitlebar" &            Gt <intent-filter> <action android:name= "Android.intent.action.MAIN"/> <categor        Y android:name= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> </activity> </application></manifest>

Crashhandler

Package Com.demo.exception;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.looper;import Com.demo.utils.constantutils;import com.demo.utils.PathUtils; Import com.demo.utils.log.mylog;/** * Uncaughtexception processing class, when the program occurs uncaught exception, there is this class to take over the program, and record send error report. * * @author User * Implements Uncaughtexceptionhandler interface */public class Crashhandler implements uncaughtexceptionhandler{Publi    C static final String TAG = "bug";    The system default Uncaughtexception processing class private Thread.uncaughtexceptionhandler mdefaulthandler; CrashhandlerInstance private static Crashhandler INSTANCE = new Crashhandler ();    The context object of the program is 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 that there is only one Crashhandler instance */Private Crashhandler () {}/** get Crashhandler instance, Singleton mode */public static Crashhan    Dler getinstance () {return INSTANCE;        }/** * Initialize * * @param context */public void init (context context) {Mcontext = context;        Gets the system default Uncaughtexception processor Mdefaulthandler = 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 */@Override public void uncaughtexception (thread thread, throwable Ex) {if (!handleexception (ex) && MdefaulthaNdler! = null) {//If the user does not process then let the system default exception handler handle mdefaulthandler.uncaughtexception (thread, ex);            } else {try {thread.sleep (3000);            } catch (Interruptedexception e) {mylog.e (TAG, "error:", e);            } mdefaulthandler.uncaughtexception (thread, ex);            Exit Program//Android.os.Process.killProcess (Android.os.Process.myPid ());        System.exit (1);     }}/** * Custom error handling, collect error messages to send error reports and so on 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 () {@Override public void run () {                Looper.prepare (); Toast.maketext (Mcontext, "I'm sorry, ChengAn exception to the sequence, which is about to exit. ", Toast.length_long). Show ();            Looper.loop ();        }}.start ();        Collect equipment parameter information collectdeviceinfo (MCONTEXT);        Save log file mylog.i (TAG, "ex:" + ex.tostring () + "--" + ex.getlocalizedmessage ());        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) {mylog.e (TAG, "An error occured when collect packAge Info ", e);        } field[] fields = Build.class.getDeclaredFields ();            for (Field field:fields) {try {field.setaccessible (true);            } catch (Exception e) {mylog.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 */PRI        Vate String Savecrashinfo2file (Throwable ex) {StringBuffer SB = new StringBuffer (); For (map.entry<string, string> entry:infos.entrySet ())//{//String ke        y = Entry.getkey ();        String value = Entry.getvalue ();        Sb.append (key + "=" + value + "\ n");        } writer = new StringWriter ();        PrintWriter printwriter = new PrintWriter (writer);        Ex.printstacktrace (PrintWriter); Throwable cause = Ex.getcausE ();            while (cause! = null) {MYLOG.I (TAG, "Cause:" + cause.tostring () + "--");            Cause.printstacktrace (PrintWriter);        Cause = Cause.getcause ();        } printwriter.close ();        String result = Writer.tostring ();        MYLOG.I (TAG, "Result:" + result);        Sb.append (result);            try {long timestamp = System.currenttimemillis ();            String time = Formatter.format (new Date ());            String fileName = "crash-" + Time + "-" + timestamp + ". Log";            if (constantutils.isonline) {fileName = "crash-online.log";            } String path = Pathutils.bugpath;            FileOutputStream fos = new FileOutputStream (path + fileName);            Fos.write (Sb.tostring (). GetBytes ());            Fos.close ();        return fileName;        } catch (Exception e) {mylog.e (TAG, "An error occured while writing file ...", e); } RETUrn null; }}
The above information relates to several classes Constantutils,pathutils and MyLog

Constantutils

public class constantutils{    /*** whether the online version ***/public    final static Boolean isOnline = false;    /***     * Time format */public    static String TimeFormat = "Yyyy-mm-dd HH:mm:ss";}

MyLog

Package Com.demo.utils.log;import Java.text.simpledateformat;import Java.util.date;import android.util.Log;import Com.demo.utils.constantutils;import Com.demo.utils.pathutils;public class mylog{private static String filename = "log.    TXT "; /*** * Print Log * @param tag * @param msg */public static void D (string tag, string msg) {if (!        Constantutils.isonline) {LOG.D (tag, msg);        }}/*** * Print log * @param tag * @param msg */public static void I (string tag, string msg) { if (!        Constantutils.isonline) {LOG.I (tag, msg);        }}/*** * Print log * @param tag * @param msg */public static void E (string tag, string msg) { if (!        Constantutils.isonline) {LOG.E (tag, msg); }}/*** * Print log * @param tag * @param msg */public static void E (string tag, string msg, throwab Le tr) {if (! Constantutils.isonlINE) {LOG.E (tag, MSG, TR);        }}/*** * Print log * @param tag * @param msg */public static void W (string tag, string msg) { if (!        Constantutils.isonline) {LOG.W (tag, msg); }}/*** * Write text to the log file * @param value */public static void write (String value) {if (!            Constantutils.isonline) {String newvalue = getDataFormat (System.currenttimemillis ()) + "" + value;        Logutils.getinstances (). Write (Pathutils.logpath, filename, newvalue); }}/*** * Gets the current time * @param timeinmillis * @return * */private static String getDataFormat (Long Tim        Einmillis) {SimpleDateFormat DataFormat = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");    Return Dataformat.format (New Date (Timeinmillis)); }}

Pathutils

Package Com.demo.utils;import Java.io.file;import Android.os.environment;public class pathutils{public    final static String Sdcardpath = Environment.getexternalstoragedirectory () + "";    Public final static String PATH = Sdcardpath + "/exception/" + apputils.getapppackagename ();    Public final static String Bugpath = PATH + "/bug/";    Public final static String LOGPATH = PATH + "/log/";    Public Pathutils ()    {        file PATH = new File (pathutils.path);        if (! Path.exists ())        {            path.mkdirs ();        }        File LOGPATH = new file (Pathutils.logpath);        if (! Logpath.exists ())        {            logpath.mkdirs ();        }        File Bugpath = new file (Pathutils.bugpath);        if (! Bugpath.exists ())        {            bugpath.mkdirs ();}}    }



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.