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

时间:2017-08-28 15:25:24

标签: android uncaughtexceptionhandler

我已经设置了UncaughtExceptionHandler,这样当我的应用程序崩溃时,我就可以将堆栈跟踪写入磁盘。我像这样设置这个处理程序:

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

     Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);
}

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

我在onCreate的{​​{1}}中调用了上述代码,但它似乎只在第一次启动任何Activity时触发。

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

2 个答案:

答案 0 :(得分:0)

来自docs

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

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

答案 1 :(得分:0)

  

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

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

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

有关详细信息,请参阅How to change crash message in android(if possible)

Here是我的crashlogger的gpl-v3 +代码,它将logcat条目写入文件。

它在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_CONTEXTHugeImageLoader.LOG_TAG,... 是我的代码的不同模块的android日志标记使用像这样

Log.d(HugeImageLoader.LOG_TAG, "some log message from modul HugeImageLoader)
相关问题