如何在运行时确定改造版本?

How can I determine the version of retrofit at runtime?

是否可以在运行时检索改造版本?我想在调试屏幕中显示此信息。

免责声明:此答案假设您正在使用 Gradle 构建您的 Android 项目。另外,我不是 Gradle 专家,所以这种方法可能存在我不知道的缺点。

虽然在代码中没有明显的方法可以做到这一点,但您可以使用 Gradle 在 BuildConfig 中创建一个简单的字段。考虑以下因素:

/**
 * Adds a public static String field to BuildConfig containing
 * the Retrofit version, no matter what build type is used.
 */
task createRetrofitBuildConfigField << {
    project.configurations.compile.each {
        if (it.name.contains("retrofit")) {
            android.buildTypes.each { flavor ->
                def version = it.name.replaceFirst(~/\.[^\.]+$/, "") // Removes extension.
                flavor.buildConfigField("String", "RETROFIT_VERSION", "\"${version}\"")
            }
        }
    }
}

preBuild.dependsOn createRetrofitBuildConfigField

当您重建项目时,一个静态字段被添加到 BuildConfig,可以在代码中轻松访问:

public static final String RETROFIT_VERSION = "retrofit-2.0.0-beta2";

您可能想将以上代码添加到 build.gradle 声明 Retrofit 依赖项的地方。