吐司没有出现在UncaughtExceptionHandler的了吐司、出现在、UncaughtExceptionHandler

2023-09-06 03:28:28 作者:龌龊掌门〃

我用这code来处理这可能会导致我的应用程序崩溃,任何未捕获的异常。

I am using this code to handle any uncaught exceptions which might cause my application to crash.

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之称,但它必须出现在它的面包,还没有显示出来。

When i run it with a known but uncaught exception(just to test), activity "CrashActivity" is called but the Toast which must come before it is not showing up.

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

Actually i wanted to show only Toast and then call myContext.finish(); instead of going to the CrashActivity. But that toast in not visible.

我在哪里错了?

推荐答案

您可能正在从一个线程调用吐司,而敬酒应该从UI线程调用......

You are probably calling the Toast from a thread while a toast should be called from the UI thread...

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

If this isn't helping, please provide us the logcat output so we can see what kind of error you are getting.