88import android .support .annotation .NonNull ;
99import android .support .annotation .RequiresPermission ;
1010
11+ import java .io .BufferedWriter ;
1112import java .io .File ;
1213import java .io .FileWriter ;
1314import java .io .IOException ;
1415import java .io .PrintWriter ;
16+ import java .io .StringWriter ;
1517import java .lang .Thread .UncaughtExceptionHandler ;
1618import java .text .Format ;
1719import java .text .SimpleDateFormat ;
@@ -85,9 +87,21 @@ public void uncaughtException(final Thread t, final Throwable e) {
8587 }
8688 return ;
8789 }
88- if (sOnCrashListener != null ) {
89- sOnCrashListener .onCrash (e );
90+
91+ StringBuilder sb = new StringBuilder ();
92+ sb .append (CRASH_HEAD );
93+ StringWriter sw = new StringWriter ();
94+ PrintWriter pw = new PrintWriter (sw );
95+ e .printStackTrace (pw );
96+ Throwable cause = e .getCause ();
97+ while (cause != null ) {
98+ cause .printStackTrace (pw );
99+ cause = cause .getCause ();
90100 }
101+ pw .flush ();
102+ sb .append (sw .toString ());
103+ final String crashInfo = sb .toString ();
104+
91105 Date now = new Date (System .currentTimeMillis ());
92106 String fileName = FORMAT .format (now ) + ".txt" ;
93107 final String fullPath = (dir == null ? defaultDir : dir ) + fileName ;
@@ -98,25 +112,28 @@ public void uncaughtException(final Thread t, final Throwable e) {
98112 sExecutor .execute (new Runnable () {
99113 @ Override
100114 public void run () {
101- PrintWriter pw = null ;
115+ BufferedWriter bw = null ;
102116 try {
103- pw = new PrintWriter (new FileWriter (fullPath , false ));
104- pw .write (CRASH_HEAD );
105- e .printStackTrace (pw );
106- Throwable cause = e .getCause ();
107- while (cause != null ) {
108- cause .printStackTrace (pw );
109- cause = cause .getCause ();
110- }
117+ bw = new BufferedWriter (new FileWriter (fullPath , false ));
118+ bw .write (crashInfo );
111119 } catch (IOException e ) {
112120 e .printStackTrace ();
113121 } finally {
114- if (pw != null ) {
115- pw .close ();
122+ if (bw != null ) {
123+ try {
124+ bw .close ();
125+ } catch (IOException e1 ) {
126+ e1 .printStackTrace ();
127+ }
116128 }
117129 }
118130 }
119131 });
132+
133+ if (sOnCrashListener != null ) {
134+ sOnCrashListener .onCrash (crashInfo , e );
135+ }
136+
120137 if (DEFAULT_UNCAUGHT_EXCEPTION_HANDLER != null ) {
121138 DEFAULT_UNCAUGHT_EXCEPTION_HANDLER .uncaughtException (t , e );
122139 }
@@ -239,6 +256,6 @@ private static boolean isSpace(final String s) {
239256 }
240257
241258 public interface OnCrashListener {
242- void onCrash (Throwable e );
259+ void onCrash (String crashInfo , Throwable e );
243260 }
244261}
0 commit comments