如何检查android库中的debuggable或debug构建类型?

Far*_*ihi 7 java android android-studio android-gradle-plugin android-buildconfig

我有一个Android AAR库.我想对我的库的消费者应用程序强加的一个安全策略是,当它debuggable为true或者使用the创建apk 时,它必须无法使用我的库.debug buildType.

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

mat*_*rix 7

有一个反射的解决方法,以获得项目的(而不是库的)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;
}
Run Code Online (Sandbox Code Playgroud)

DEBUG例如,要获取该字段,只需从库中调用它Activity:

boolean debug = (Boolean) getBuildConfigValue(this, "DEBUG");
Run Code Online (Sandbox Code Playgroud)

我还没有尝试过这个并不能保证它会一直有效但你可以继续!


fre*_*wed 5

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

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