【问题标题】:How to check debuggable or debug build type in android library?如何在 android 库中检查可调试或调试构建类型?
【发布时间】:2017-09-29 16:12:00
【问题描述】:

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

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

【问题讨论】:

  • 你可以检查你的库的build.gradle来检测它是否调试但是你将如何检查消费者的build.gradle
  • @KostasDrakonakis 这正是问题所在:)
  • @FarhadFaghihi 但原因是什么?重要的一点是您的库未处于调试状态。每个人都在调试模式下开发应用程序。
  • @GabrieleMariotti 这是针对消费者应用程序发布的安全检查,该应用程序将分发给最终用户。
  • 你可以像这样getApplicationContext().getResources().getString("BuildConfig Res Value")

标签: java android android-studio android-gradle-plugin android-buildconfig


【解决方案1】:

有一种使用反射的解决方法,以便像这样获得项目的(不是库的)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 中将 minifyEnabled 设置为 true,这将不起作用并返回 null。这不是在库中使用的推荐方法。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2016-05-04
    • 2011-10-28
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多