使用gradle定义全局变量

考虑到很多时候调试过程中需要用的打印日志和 Toast 信息都不需要在正式发行版本中出现,常用的做法便是定义全局变量用于区分两种阶段的所需要达到的效果。那么通过在 gradle 中添加全局变量,可以简单方便的定义全局均可使用的变量,怎么做到的呢,来看看伐~

找到本次项目中的 App 所依赖的 gradle 文件(build.gradle(Modle:app)),其中的 buildTypes 部分如下:

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}   

从上面的代码可以看出,buildTypes 中默认存在 release 模式,即正式发布版本,其中包含两个变量,其含义如下:

  • minifyEnabled 其中,true表示进行代码加密,false表示不加密

  • proguardFiles 表示代码加密原则,存在两个文件对,getDefaultProguardFile(‘proguard-android.txt’)表示默认文件,这个文件是sdk自带的,有一些通用的配置;但是如果apk需要更加严格的加密,我们可以在’proguard-rules.pro’文件中进行更加详尽的配置。

对应 release ,那么我们添加 debug 模式即可,下面以添加两个全局变量(分别是全局链接和全局Log打印控制变量)为例添加 debug 部分,代码如下:

buildTypes {
    release {
        //发布模式的常量
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        buildConfigField("String", "HTTP_BASE", '"https://www.baidu.com/api/release/"')
        buildConfigField("boolean","IsLogShow","false")
    }
    debug {
        //测试模式的常量
        buildConfigField("String", "HTTP_BASE", '"https://www.baidu.com/api/debug"')
        buildConfigField("boolean","IsLogShow","true")
    }
}

那么,为什么可以这样加呢?就要从 buildConfigField 的源文件看起了,

/**
 * Adds a new field to the generated BuildConfig class.
 *
 * <p>The field is generated as: <code>&lt;type&gt; &lt;name&gt; = &lt;value&gt;;</code>
 *
 * <p>This means each of these must have valid Java content. If the type is a String, then the
 * value should include quotes.
 *
 * @param type the type of the field
 * @param name the name of the field
 * @param value the value of the field
 */
public void buildConfigField(
        @NonNull String type,
        @NonNull String name,
        @NonNull String value) {
    ClassField alreadyPresent = getBuildConfigFields().get(name);
    if (alreadyPresent != null) {
        logger.info(
                "BuildType(${getName()}): buildConfigField '$name' value is being replaced: ${alreadyPresent.value} -> $value");
    }
    addBuildConfigField(AndroidBuilder.createClassField(type, name, value));
}

从上面代码可以看出,buildConfigField 方法需要传入三个字符串类型的变量,第一个为要定义的常量的类型,第二个为该常量的命名,第三个为该常量的值。

当然,这些我们定义的常量肯定可以在某个文件中查到对吧,在哪里呢?Android Studio 中切换到 Project 模式,打开如下路径:

app -> build -> generated -> source -> buildConfig -> debug -> 包名 -> BuildConfig

打开这个 BuildConfig 文件,就可以看到我们定义的所有的全局常量了~

猜你喜欢

转载自blog.csdn.net/baidu_33221362/article/details/79875011
今日推荐