如何在Android库中检查debuggable或debug构建类型?

12

我有一个 Android AAR 库。 我想对我的库的消费者应用强制执行一个安全策略,即当 debuggable 为 true 或 apk 是使用 debug buildType 创建时,其不得使用我的库。

我该如何在 Android 中以编程方式检查这一点?


你可以检查库的 build.gradle 文件来确定它是否为调试版本,但是你如何检查消费者的 build.gradle 文件呢? - matrix
@KostasDrakonakis 这正是问题的所在 :) - Farhad
@FarhadFaghihi 但是原因是什么呢?重要的一点是你的库不在调试模式下。每个人都会在调试模式下开发应用程序。 - Gabriele Mariotti
@GabrieleMariotti 这是针对消费者应用程序发布的安全检查,该应用程序将分发给最终用户。 - Farhad
你可以像这样在BuildConfig中获取值:getApplicationContext().getResources().getString("BuildConfig Res Value") - Madhukar Hebbar
2个回答

11

检查AndroidManifest文件中的debuggable标签是更好的方法:

public static boolean isDebuggable(Context context) {
    return ((context.getApplicationInfo().flags 
            & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
}

8

有一个通过反射来获取项目(而不是库)的BuildConfig值的解决方法,如下所示:

/**
 * Gets a field from the project's BuildConfig. This is useful when, for example, flavors
 * are used at the project level to set custom fields.
 * @param context       Used to find the correct file
 * @param fieldName     The name of the field-to-access
 * @return              The value of the field, or {@code null} if the field is not found.
 */
public static Object getBuildConfigValue(Context context, String fieldName) {
    try {
        Class<?> clazz = Class.forName(context.getPackageName() + ".BuildConfig");
        Field field = clazz.getField(fieldName);
        return field.get(null);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return null;
}

例如,要获取DEBUG字段,只需从库Activity中调用此函数:

boolean debug = (Boolean) getBuildConfigValue(this, "DEBUG");

我还没有尝试过这个方法,不能保证它一直有效,但你可以尝试一下!!!


1
看起来很正常。我会尝试并告诉你结果。 - Farhad
如果在应用的 build.gradle 中将 minifyEnabled 设置为 true,则此方法将无法运行并返回 null。这不是在库中使用的推荐方法。 - Ashwin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接