Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/224.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在android库中检查可调试或调试构建类型?_Java_Android_Android Studio_Android Gradle Plugin_Android Buildconfig - Fatal编程技术网

Java 如何在android库中检查可调试或调试构建类型?

Java 如何在android库中检查可调试或调试构建类型?,java,android,android-studio,android-gradle-plugin,android-buildconfig,Java,Android,Android Studio,Android Gradle Plugin,Android Buildconfig,我有一个安卓AAR库。我想对我的库的使用者应用程序施加的一个安全策略是,当debugable为true或使用debug buildType创建apk时,它不能使用我的库。 如何在android中以编程方式检查此问题?有一种解决方法,可以通过反射获得项目(而不是库)的BuildConfig值,如下所示: /** * Gets a field from the project's BuildConfig. This is useful when, for example, flavors * a

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


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

有一种解决方法,可以通过反射获得项目(而不是库)的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;
}

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

检查AndroidManifest文件上的可调试标记是更好的方法:

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

您可以检查库的
build.gradle
以检测其是否调试,但您将如何检查消费者的
build.gradle
?@KostasDrakonakis这正是问题所在:)@Farhadfaghi但原因是什么?重要的一点是,您的库未处于调试状态。每个人都在调试模式下开发应用程序。@GabrieleMariotti这是对即将分发给最终用户的消费者应用程序版本的安全检查。您可以在buildconfig中获得如下值
getApplicationContext().getResources().getString(“Config BuildRes value”)
似乎合法。我将尝试让您知道结果。如果在应用程序的build.gradle中将minifyEnabled设置为true,则此操作将不起作用并返回null。这不是建议在库中使用的方法。
public static boolean isDebuggable(Context context) {
    return ((context.getApplicationInfo().flags 
            & ApplicationInfo.FLAG_DEBUGGABLE) != 0);
}