我有一个 Android AAR 库。 我想对我的库的消费者应用强制执行一个安全策略,即当 debuggable
为 true 或 apk 是使用 debug buildType
创建时,其不得使用我的库。
我该如何在 Android 中以编程方式检查这一点?
我有一个 Android AAR 库。 我想对我的库的消费者应用强制执行一个安全策略,即当 debuggable
为 true 或 apk 是使用 debug buildType
创建时,其不得使用我的库。
我该如何在 Android 中以编程方式检查这一点?
检查AndroidManifest文件中的debuggable
标签是更好的方法:
public static boolean isDebuggable(Context context) {
return ((context.getApplicationInfo().flags
& ApplicationInfo.FLAG_DEBUGGABLE) != 0);
}
有一个通过反射来获取项目(而不是库)的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");
我还没有尝试过这个方法,不能保证它一直有效,但你可以尝试一下!!!
build.gradle
文件来确定它是否为调试版本,但是你如何检查消费者的build.gradle
文件呢? - matrixgetApplicationContext().getResources().getString("BuildConfig Res Value")
- Madhukar Hebbar