How to disable Firebase Crash Reporting when the app is running on debug?

后端 未结 16 1328
谎友^
谎友^ 2020-12-04 13:42

I have successfully implemented Firebase Crash Reporting, but I need to disable the service when the app is running undo the \'debug\' Build Variant, in order to avoid non-r

16条回答
  •  眼角桃花
    2020-12-04 14:47

    As has been said before - there is no official way to do this. But the worst workaround for me as mentioned @mark-d is to reset DefaultUncaughtExceptionHandler (https://stackoverflow.com/a/39322734/4245651).

    But if you just call System.exit(2) as was suggested - the app will be instantly closed on exception, without any dialog message and hard getting debug logs. If this is important to you, there is a way to restore default handler:

    if (BuildConfig.DEBUG) {
            final Thread.UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
            if (currentHandler.getClass().getPackage().getName()
                                                    .startsWith("com.google.firebase")) {
                final Thread.UncaughtExceptionHandler defaultHandler = 
                    getPrivateFieldByType(currentHandler, Thread.UncaughtExceptionHandler.class);
                Thread.setDefaultUncaughtExceptionHandler(defaultHandler);
            }
    }
    

    Where

    public static  T getPrivateFieldByType(Object obj, Class fieldType) {
        if (obj != null && fieldType != null) {
            for (Field field : obj.getClass().getDeclaredFields()) {
                if (field.getType().isAssignableFrom(fieldType)) {
                    boolean accessible = field.isAccessible();
                    if (!accessible) field.setAccessible(true);
                    T value = null;
                    try {
                        //noinspection unchecked
                        value = (T) field.get(obj);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    if (!accessible) field.setAccessible(false);
                    return value;
                }
            }
        }
        return null;
    }
    

提交回复
热议问题