Skip to content

Commit f2f3515

Browse files
committed
Update
1 parent 15bbd60 commit f2f3515

1 file changed

Lines changed: 18 additions & 10 deletions

File tree

app/src/main/java/com/tool/tree/CrashHandler.java

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@
77
public class CrashHandler implements Thread.UncaughtExceptionHandler {
88

99
private final Context context;
10-
private final Thread.UncaughtExceptionHandler defaultHandler;
10+
private final Thread.UncaughtExceptionHandler defaultHandler; // ← Thêm khai báo này
1111

1212
public CrashHandler(Context context) {
1313
this.context = context.getApplicationContext();
14-
this.defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
14+
this.defaultHandler = Thread.getDefaultUncaughtExceptionHandler(); // ← Lưu default handler
1515
}
1616

1717
@Override
@@ -20,24 +20,32 @@ public void uncaughtException(Thread thread, Throwable ex) {
2020
String stackTrace = Log.getStackTraceString(ex);
2121
Log.e("CrashHandler", "Uncaught exception in thread: " + thread.getName(), ex);
2222

23+
// (Tùy chọn) Lưu log vào file nếu bạn có implement
24+
// CrashFileWriter.write(context, stackTrace);
25+
2326
Intent intent = new Intent(context, CrashLogActivity.class);
2427
intent.putExtra("crash_log", stackTrace);
25-
// Quan trọng: Phải có FLAG_ACTIVITY_NEW_TASK vì gọi từ thread không phải UI
26-
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
27-
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
28+
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
29+
| Intent.FLAG_ACTIVITY_CLEAR_TASK
30+
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
2831

2932
context.startActivity(intent);
3033

3134
} catch (Throwable t) {
3235
Log.e("CrashHandler", "Failed to handle crash gracefully", t);
33-
} finally {
34-
// Kết thúc process cũ để CrashLogActivity có thể chạy trên một môi trường sạch
35-
android.os.Process.killProcess(android.os.Process.myPid());
36-
System.exit(10);
36+
}
37+
38+
// Luôn gọi default handler ở đây (ngoài try-catch) để:
39+
// - Đảm bảo logcat có stack trace chuẩn (tag AndroidRuntime)
40+
// - Process được kill đúng cách
41+
// - Dialog "App đã dừng" xuất hiện nếu startActivity fail hoặc bạn muốn fallback
42+
if (defaultHandler != null) {
43+
defaultHandler.uncaughtException(thread, ex);
3744
}
3845
}
3946

47+
// Phương thức tiện lợi để cài đặt (gọi 1 lần trong Application.onCreate)
4048
public static void install(Context context) {
4149
Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(context));
4250
}
43-
}
51+
}

0 commit comments

Comments
 (0)