0

我设置了一个UncaughtExceptionHandler, 以便在我的应用程序崩溃时将堆栈跟踪写入磁盘。我这样设置这个处理程序:

if (!(Thread.getDefaultUncaughtExceptionHandler() instanceof CustomExceptionHandler)) {
         exceptionHandler = new CustomExceptionHandler(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(),
                null, this);

     Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);
}

在哪里CustomExceptionHandler实现UncaughtExceptionHandler。我将实例保存在 my 中Activity,因此我可以将其用于其他一些功能(删除堆栈跟踪、检索它们等)。

onCreate我在my中调用了上面的代码Activity,但它似乎只在第一次Activity运行 any 时触发。

我看到Thread.setDefaultUncaughtExceptionHandler调用是静态的,这是否意味着我只能在我的应用程序中设置该处理程序一次?或者我可以为每个线程设置它吗?

4

2 回答 2

0

来自文档

 * Sets the default uncaught exception handler. This handler is invoked in
 * case any Thread dies due to an unhandled exception.

是的,这个处理程序是全局的,你需要为每个应用设置一次

于 2017-08-28T15:59:58.680 回答
0

UncaughtExceptionHandler 是否设置应用程序范围?

是的。如果您在活动中设置它并且活动被销毁,则活动中的处理程序代码可能不再存在。

我已经在 Application-onCreate 中设置了处理程序(而不是在 Activity 中),因此它适用于属于 Application 的所有 Activity 以写入崩溃日志。

有关详细信息,请参阅如何在 android 中更改崩溃消息(如果可能)

是用于将 logcat 条目写入文件的崩溃记录器的 gpl-v3+ 代码。

它像这样在Application.onCreate中初始化

public class AndroFotoFinderApp extends Application {
    private LogCat mCrashSaveToFile = null;

    @Override public void onCreate() {
        super.onCreate();

        mCrashSaveToFile = new LogCat(this, Global.LOG_CONTEXT, HugeImageLoader.LOG_TAG,
                PhotoViewAttacher.LOG_TAG, CupcakeGestureDetector.LOG_TAG,
                FotoLibGlobal.LOG_TAG, ThumbNailUtils.LOG_TAG, IMapView.LOGTAG,
                ExifInterface.LOG_TAG, ImageMetaReader.LOG_TAG);
    }
}

其中常量 Global.LOG_CONTEXT,,HugeImageLoader.LOG_TAG...是我的代码使用的不同模块的android日志记录标签,如下所示

Log.d(HugeImageLoader.LOG_TAG, "some log message from modul HugeImageLoader)
于 2017-08-28T16:12:09.473 回答