处理未处理的异常并显示警报

时间:2016-10-11 17:55:39

标签: android

我使用以下代码向用户显示一个对话框,但它不起作用。在没有显示对话框的情况下,屏幕在异常时消失。如何使此代码显示带有异常详细信息的对话框,并在按下确定后退出?

public class MyApplication extends MultiDexApplication
{

    @Override
    public void onCreate() {
        super.onCreate();
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
        {
            @Override
            public void uncaughtException(Thread thread, Throwable ex)
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
                builder.setPositiveButton("OK",null);
                builder.setTitle("An error occured");
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        try { Thread.sleep(1000); }
                        catch (Exception ex) {}
                        dialog.dismiss();
                        System.exit(1);
                    }
                });
                builder.setMessage(ex.getStackTrace().toString());
                AlertDialog alert = builder.create();
                alert.show();
            }
        });
    }
}

活动

public void Login_Click(View v)
{
    throw new RuntimeException("");
}

0 个答案:

没有答案