当我的 android 应用程序抛出异常时,我想显示一个自定义对话框来告诉用户发生了错误,所以我使用Thread.setDefaultUncaughtExceptionHandler
设置一个全局异常处理程序:
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();
}
});
}
}
但我发现它抛出了任何异常,AlertDialog
不会显示,而是应用程序阻塞,过了一会儿,它会显示一个系统对话框:
X app is not responding. Would you like to close it?
Wait | OK
我现在该怎么办?
更新
日志:
11-16 12:54:16.017: WARN/WindowManager(90): Attempted to add window with non-application token WindowToken{b38bb6a8 token=null}. Aborting.
似乎错误来自new AlertDialog.Builder(getApplicationContext());
但这是Application
子类中的异常处理程序,我该如何为其设置活动实例?