中设置全局未捕获异常处理程序的理想方法

中设置全局未捕获异常处理程序的理想方法

本文介绍了在 Android 中设置全局未捕获异常处理程序的理想方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的 Android 应用程序中的所有线程设置一个全局未捕获异常处理程序.因此,在我的 Application 子类中,我将 Thread.UncaughtExceptionHandler 的实现设置为未捕获异常的默认处理程序.

I want to set a global uncaught exception handler for all the threads in my Android application. So, in my Application subclass I set an implementation of Thread.UncaughtExceptionHandler as default handler for uncaught exceptions.

Thread.setDefaultUncaughtExceptionHandler(
                new DefaultExceptionHandler(this));

在我的实现中,我试图显示一个 AlertDialog 显示适当的异常消息.

In my implementation, I am trying to display an AlertDialog displaying appropriate exception message.

但是,这似乎不起作用.每当任何未处理的线程抛出异常时,我都会得到库存的操作系统默认对话框(对不起!-Application-has-stopped-unexpectedly dialog").

However, this doesn't seem to work. Whenever, an exception is thrown for any thread which goes un-handled, I get the stock, OS-default dialog ("Sorry!-Application-has-stopped-unexpectedly dialog").

为未捕获的异常设置默认处理程序的正确和理想方法是什么?

What is the correct and ideal way to set a default handler for uncaught exceptions?

推荐答案

这应该就是你需要做的.(确保之后停止进程——事情可能处于不确定状态.)

That should be all you need to do. (Make sure you cause the process to halt afterward -- things could be in an uncertain state.)

首先要检查的是 Android 处理程序是否仍在被调用.有可能您的版本正在被调用但致命地失败,并且 system_server 在看到进程崩溃时显示一个通用对话框.

The first thing to check is whether the Android handler is still getting called. It's possible that your version is being called but failing fatally and the system_server is showing a generic dialog when it sees the process crash.

在您的处理程序顶部添加一些日志消息以查看它是否到达那里.从 getDefaultUncaughtExceptionHandler 打印结果,然后抛出未捕获的异常导致崩溃.密切关注 logcat 输出,看看发生了什么.

Add some log messages at the top of your handler to see if it's getting there. Print the result from getDefaultUncaughtExceptionHandler and then throw an uncaught exception to cause a crash. Keep an eye on the logcat output to see what's going on.

这篇关于在 Android 中设置全局未捕获异常处理程序的理想方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 03:33