An Android app crashes after an exception is captured and restarted and written to the log

Source: Internet
Author: User
Tags dateformat save file throwable

In the development of Android, sometimes due to some exceptions caused by the application error, occasionally crash due to errors, resulting in a drop in user experience, in order to solve this problem, we have to deal with such an exception: The code is as follows: Crashhandler.java
Import Android.content.context;import android.content.Intent; 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.util.log;import android.widget.Toast;
Import com......activity. Splashactivity;import Com.......util. Imgcliputil;
Import Java.io.file;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;
/** * Uncaughtexception processing class, when the program occurs uncaught exception, there is the class to take over the program, and record send error report. * * @author User * */public class Crashhandler implements Uncaughtexceptionhandler {
public static final String TAG = "Crashhandler";
Crashhandler instance private static Crashhandler INSTANCE = new Crashhandler ();
The context object of the program is private context Mcontext;
The system default Uncaughtexception processing class private Thread.uncaughtexceptionhandler mdefaulthandler;
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");

/** guarantees that there is only one Crashhandler instance */Private Crashhandler () {}
/** get Crashhandler instance, Singleton mode */public static Crashhandler 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 E        x) {//delete crop left in cached photo Imgcliputil.deleteallfiles (Imgcliputil.imgclippath); if (!handleexception (ex) && Mdefaulthandler! = null) {//If the user does not handle it, let the system default exception handler handle the Mdefaultha        Ndler.uncaughtexception (thread, ex);            } else {try {thread.sleep (2000);            } catch (Interruptedexception e) {log.e (TAG, "error:", e); }
Exit the program, note the following Reboot Launcher Code///Android.os.Process.killProcess (Android.os.Process.myPid ());//System.exit (1)            ;            Restart the program, commenting the exit program above Intent Intent = new Intent ();            Intent.setclass (Mcontext, Splashactivity.class);            Intent.addflags (Intent.flag_activity_new_task);            Mcontext.startactivity (Intent);        Android.os.Process.killProcess (Android.os.Process.myPid ()); }    }
/** * Custom error handling, collecting error messages, sending error reports and so on are done here * * @param ex * @return true: If the exception information is processed; otherwise false */private B        Oolean HandleException (Throwable ex) {if (ex = = null) {return false; }
Use Toast to display exception information new Thread () {@Override public void run () {Looper.prepar                E (); Toast.maketext (Mcontext, "Sorry, the program has an exception and is about to exit.)                ", Toast.length_long). Show ();            Looper.loop (); }}.start ();
Collect equipment parameter information collectdeviceinfo (MCONTEXT);        Save log file Savecrashinfo2file (ex);    return true; }
/** * Collect device parameter information * @param CTX */public void Collectdeviceinfo (Context ctx) {try {Package            Manager 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 (T        Hrowable ex) {StringBuffer SB = new StringBuffer ();            For (map.entry<string, string> entry:infos.entrySet ()) {String key = Entry.getkey ();            String value = Entry.getvalue ();        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 ();        Sb.append (result);            try {long timestamp = System.currenttimemillis ();            String time = Formatter.format (new Date ()); String fileName = "crash-" + Time + "-" + timestamp + ". Log";
if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {String Path = "/sdcard/tpage                s/crash/";                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; }}
myapplication.java/** * Created by IT01 on 2015/10/28 0028. */public class MyApplication extends application {/* private refwatcher mrefwatcher;
public static Refwatcher Getrefwatcher (context context) {MyApplication application = (MyApplication) Context.getap        Plicationcontext ();    return application.mrefwatcher; }*/
@Override public void OnCreate () {super.oncreate ();//Mrefwatcher = Leakcanary.install (this);        The cookie policy allows Okhttp to accept all cookie/* cookiemanager Cookiemanager = new Cookiemanager (); Okhttp.setcookie (Cookiemanager); * *
if (Constants.Config.DEVELOPER_MODE && Build.VERSION.SDK_INT >= build.version_codes. Gingerbread) {Strictmode.setthreadpolicy (New StrictMode.ThreadPolicy.Builder (). Detectall (). Penaltydialog (). Bui            LD ());        Strictmode.setvmpolicy (New StrictMode.VmPolicy.Builder (). Detectall (). Penaltydeath (). build ()); } if (Android.os.Build.VERSION.SDK_INT > 9) {strictmode.threadpolicy policy = new STRICTMODE.THREADP Olicy.            Builder (). Permitall (). build ();        Strictmode.setthreadpolicy (Policy); }
Crashhandler Crashhandler = Crashhandler.getinstance ();//Crashhandler.init (Getapplicationcontext ());  
}  
}

Imgcliputil.javaimport Android.graphics.bitmap;import Android.graphics.Matrix;
Import Java.io.bufferedoutputstream;import java.io.file;import Java.io.fileoutputstream;import java.io.IOException ;
/** * Created by IT01 on 2015/12/14 0014.        */public class Imgcliputil {public static Boolean isclip (Bitmap bit) {int w = bit.getwidth ();//Get picture width, height        int h = bit.getheight ();        if ((w==h) &&w<1080) return false;    return true; The public static int getsquaresize (Bitmap bit) {int w = bit.getwidth ();//Gets the width of the picture, high int h = bit.getheight (        ); int WH = w > h? h:w;//the square area to be taken after trimming return WH > 1080?    1080:WH; }
public static Bitmap Scalebitmap (Bitmap Bitmap, int edgelength) {
if (null = = Bitmap | | edgelength <= 0) {return null; }
Bitmap result = Bitmap;        int widthorg = Bitmap.getwidth (); int heightorg = Bitmap.getheight ();
        if (widthorg >= edgelength && heightorg >= edgelength)         {           //compress to a minimum length of edgelength bitmap            INT lon Geredge = (int) (Edgelength * Math.max (widthorg, heightorg)/Math.min (widthorg, heightorg));        &N Bsp   int scaledwidth = widthorg > heightorg? longeredge:edgelength;            int scaledheight = widthorg > heightorg? edgelength:longeredge;            Bitmap scaledbitmap;          & nbsp try{                Scaledbitmap = Bitmap.createscaledbitmap (Bitmap, Scaledwidth, Scaledheight, True);           }            catch (Exception e) {                return null;      &NBSP    }
Intercept the square part in the middle.            int xtopleft = (scaledwidth-edgelength)/2; int ytopleft = (scaledheight-edgelength)/2;
try{result = Bitmap.createbitmap (Scaledbitmap, Xtopleft, Ytopleft, Edgelength, edgelength);            Scaledbitmap.recycle ();            } catch (Exception e) {return null; }        }
return result; }
/** * Save File * @param BM * @param fileName * @throws IOException */public static void SaveFile (Bitma        P BM, String fileName) throws IOException {string path =imgclippath+ "/";//"/sdcard/revoeye/";        File Dirfile = new file (path);        if (!dirfile.exists ()) {Dirfile.mkdir ();        } File Mycapturefile = new file (path + fileName);        Bufferedoutputstream BOS = new Bufferedoutputstream (new FileOutputStream (Mycapturefile));        Bm.compress (Bitmap.CompressFormat.JPEG, N, BOS);        Bos.flush ();    Bos.close (); }
   //rotate pictures    /**     * rotate pictures by an angle      *     * @param bm     *             need to rotate the picture      * @param degree     *             Rotate angle      * @return rotated picture      */  &nbs P Public Bitmap Rotatebitmapbydegree (Bitmap BM, int degree) {        Bitmap RETURNBM = null;  &nbsp ;    //rotation matrix generation based on rotation angle         Matrix matrix = new Matrix ()//       matri X.postrotate (degree);        matrix.setrotate (degree, (float) bm.getwidth ()/2, (float) Bm.getheight ()/2);        Try {           //rotate the original image according to the rotation matrix and get a new picture and nbsp           RETURNBM = bitmap.createbitmap (BM, 0, 0, bm.getwidth (), Bm.getheight (), Matrix, True); & nbsp       } catch (OutOfMemoryError e) {            e.printstacktrace ();       }         if (RETURNBM = = null) {            RETURNBM = bm;    & nbsp  }        if (BM! = RETURNBM) {            bm.recycle ();  &NB Sp    }        return returnbm;   }
public static file Imgclippath =new file (Utils.getpicpath () + "img"); public static void Deleteallfiles (File root) {
        File files[] = root.listfiles ();        if (Files! = null)     &N Bsp       for (File f:files) {                if (f.isdirectory ()) { Determine if folder                     deleteallfiles (f);      &N Bsp             Try {                    &NBSP ;   F.delete ();                   } catch (Exception e) {  &nbs P                }               } else {& nbsp                   if (f.exists ()) {//Determine existence         &NBS P               deleteallfiles (f);                        Try {                        &NBS P   F.delete ();                       } catch (Exception E ) {                       }                   }               }           }   }
}


From for notes (Wiz)

An Android app crashes after an exception is captured and restarted and written to the 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.