-->

敬酒不显示的UncaughtExceptionHandler了(Toast not showing

2019-07-30 13:21发布

我使用此代码来处理任何未捕获的异常可能会导致我的应用程序崩溃。

public class ExceptionHandler implements java.lang.Thread.UncaughtExceptionHandler {
    private final Context myContext;

    public ExceptionHandler(Context context) {

        myContext = context;
    }

    public void uncaughtException(Thread thread, Throwable exception) {

        Toast.makeText(myContext,
                "The application has crashed, and a report is sent to the admin",
                Toast.LENGTH_SHORT).show();
        StringWriter stackTrace = new StringWriter();
        exception.printStackTrace(new PrintWriter(stackTrace));
        System.err.println(stackTrace);// You can use LogCat too
        Intent intent = new Intent(myContext, CrashActivity.class);
        myContext.startActivity(intent);
        Process.killProcess(Process.myPid());
        System.exit(10);
    }
}

当我与一个已知的,但是未捕获的异常(只是为了测试)运行它,活动“CrashActivity”之称,但它必须来之前它的面包,还没有显示出来。

其实我想只显示吐司,然后调用myContext.finish(); 而不是去到CrashActivity。 但在不可见的是烤面包。

我在哪里错了?

Answer 1:

你可能从一个线程调用吐司而举杯应该从UI线程调用...

如果这没有帮助,请向我们提供了logcat的输出,所以我们可以看到你做了什么样的错误。



Answer 2:

而对于谷歌搜索确切同样的问题,发现了这个问题。 至于我可以告诉它是没有必要有Toast.show()从UI线程调用,只要有一个应用程序上下文。

据我所知:这里出现的问题是:你想带一个面包和随即你的应用程序是由虚拟机,这意味着你的吐司是关机以及关机。

用于问题的解决方案如下:

  • 从sepearate的线程中运行吐司
  • 在未捕获的异常处理应用程序的延时关机。

我做的是以下几点:

Application::onCreate()

Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread thread, Throwable ex)
    {
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(getApplicationContext(), "Application crashed", Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        }.start();

        try
        {
            Thread.sleep(4000); // Let the Toast display before app will get shutdown
        }
        catch (InterruptedException e)
        {
            // Ignored.
        }
    }
});

它类同于ACRA的Toast通知如何工作(其实这就是我从提示)。



Answer 3:

调用System.exit(0)在Android中UncaughtExceptionHandler帮助应用程序从错误中恢复并重新启动最后一项活动。 恕我直言,用户体验得到改善显著。 但是,这种方法需要试验,并在多个安卓平台上的测试。 试过这对GB和JB。 它工作得很好。 此外,我从别人(我是新来的Android)是调用听到System.exit() Android中并不推荐,但..could以此为Android应用程序崩溃的一个很好的恢复选项。

    public void uncaughtException(Thread thread, Throwable ex) {
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();  
                Toast.makeText(YourActivity.this, "Application has Crashed. Recovering now.", Toast.LENGTH_LONG).show();
                /* Log relevant message/analytics from here. */
                System.exit(1);
                Looper.loop();
            }
        }.start();
    }


文章来源: Toast not showing up in UnCaughtExceptionHandler