Android Catch Unhandled Exception And Show The Dialog
I want to handle unhandled exception in my app without any third-party libraries. So i write a code. Activity : @Override public void onCreate(Bundle savedInstanceState) { supe
Solution 1:
In my case, I moved AlertDialog.Builder
in thread run function like this:
publicvoidshowToastInThread(final String str){
newThread() {
@Overridepublicvoidrun() {
Looper.prepare();
AlertDialog.Builder builder = newAlertDialog.Builder(context);
builder.setMessage("Application was stopped...")
.setPositiveButton("Report to developer about this problem.", newDialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Exit", newDialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog, int id) {
// Not worked!
dialog.dismiss();
System.exit(0);
android.os.Process.killProcess(android.os.Process.myPid());
}
});
dialog = builder.create();
Toast.makeText(context, "OOPS! Application crashed", Toast.LENGTH_SHORT).show();
if(!dialog.isShowing())
dialog.show();
Looper.loop();
}
}.start();
}
and all thing work perfectly. Hope this help you.
Solution 2:
According this post, the state of the application is unknown, when setDefaultUncaughtExceptionHandler
is called. This means that your onClick listeners may not be active anymore.
Why not use this method:
@OverridepublicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.main);
Thread.setDefaultUncaughtExceptionHandler(newReportHelper(this));
thrownewNullPointerException();
} catch (NullPointerException e) {
newReportHelper(this);
}
}
and remove ReportHelper implementing the Thread.UncaughtExceptionHandler
interface.
Your method of not explicitly catching exceptions can be seen as an anti-pattern.
Solution 3:
Since an exception occurs on the UI-Thread: the state of this thread is probably unexpected
So try simply this in your click handler :
.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog, int id) {
android.os.Process.killProcess(android.os.Process.myPid());
}
});
Post a Comment for "Android Catch Unhandled Exception And Show The Dialog"