【发布时间】:2012-11-16 12:47:04
【问题描述】:
当我的 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子类中的异常处理程序,我该如何为其设置活动实例?
【问题讨论】:
-
当应用程序花费太多时间时会出现该消息(在这种情况下不会引发异常)。我的建议是尝试将繁重的任务转移到 AsyncTask。
标签: android exception-handling android-alertdialog android-dialog