11

我有一个 Android AAR 库。我想对我的库的消费者应用程序强加的一项安全策略是,当它debuggable为 true 或 apk 是使用debug buildType.

如何在 android 中以编程方式检查这个?

4

2 回答 2

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字段,只需从 library 调用它Activity

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

我还没有尝试过,不能保证它会一直工作,但你可以继续!

于 2017-05-02T08:05:23.567 回答
7

检查debuggableAndroidManifest 文件上的标签是更好的方法:

public static boolean isDebuggable(Context context) {
    return ((context.getApplicationInfo().flags 
            & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
}
于 2020-03-07T14:30:59.463 回答