When my android application throw an exception, I want to show a custom dialog to tell user there is something wrong happened, so I use Thread.setDefaultUncaughtExceptionHandler
to set a global exception handler:
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, final Throwable ex) {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setTitle("There is something wrong")
.setMessage("Application will exit:" + ex.toString())
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// throw it again
throw (RuntimeException) ex;
}
})
.show();
}
});
}
}
But I found it there is any exception thrown, the AlertDialog
won't show, instead, the application blocks and after a while, it will show a system dialog:
X app is not responding. Would you like to close it?
Wait | OK
What should I do now?
UPDATE
The log:
11-16 12:54:16.017: WARN/WindowManager(90): Attempted to add window with non-application token WindowToken{b38bb6a8 token=null}. Aborting.
It seems the error is coming from new AlertDialog.Builder(getApplicationContext());
But this is an exception handler in Application
subclass, how can I set an activity instance to it?