2、任务task、BuildConfig、项目范围设置

Task

想要知道一个项目中有哪些任务可以被使用,可以运行./gradlew tasks查看,该命令可以打印出所有可用的任务。

hhh:MyApplication huozhenpeng$ ./gradlew tasks
Android tasks
-------------
androidDependencies - Displays the Android dependencies of the project.
signingReport - Displays the signing info for each variant.
sourceSets - Prints out all the source sets defined in this project.

Build tasks
-----------
assemble - Assembles all variants of all applications and secondary packages.
assembleAndroidTest - Assembles all the Test applications.
assembleDebug - Assembles all Debug builds.
assembleRelease - Assembles all Release builds.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
clean - Deletes the build directory.
cleanBuildCache - Deletes the build cache directory.
compileDebugAndroidTestSources
compileDebugSources
compileDebugUnitTestSources
compileReleaseSources
compileReleaseUnitTestSources
mockableAndroidJar - Creates a version of android.jar that's suitable for unit tests.

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'MyApplication'.
components - Displays the components produced by root project 'MyApplication'. [incubating]
dependencies - Displays all dependencies declared in root project 'MyApplication'.
dependencyInsight - Displays the insight into a specific dependency in root project 'MyApplication'.
dependentComponents - Displays the dependent components of components in root project 'MyApplication'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'MyApplication'. [incubating]
projects - Displays the sub-projects of root project 'MyApplication'.
properties - Displays the properties of root project 'MyApplication'.
tasks - Displays the tasks runnable from root project 'MyApplication' (some of the displayed tasks may belong to subprojects).

Install tasks
-------------
installDebug - Installs the Debug build.
installDebugAndroidTest - Installs the android (on device) tests for the Debug build.
uninstallAll - Uninstall all applications.
uninstallDebug - Uninstalls the Debug build.
uninstallDebugAndroidTest - Uninstalls the android (on device) tests for the Debug build.
uninstallRelease - Uninstalls the Release build.

Verification tasks
------------------
check - Runs all checks.
connectedAndroidTest - Installs and runs instrumentation tests for all flavors on connected devices.
connectedCheck - Runs all device checks on currently connected devices.
connectedDebugAndroidTest - Installs and runs the tests for debug on connected devices.
deviceAndroidTest - Installs and runs instrumentation tests using all Device Providers.
deviceCheck - Runs all device checks using Device Providers and Test Servers.
lint - Runs lint on all variants.
lintDebug - Runs lint on the Debug build.
lintRelease - Runs lint on the Release build.
lintVitalRelease - Runs lint on just the fatal issues in the release build.
test - Run unit tests for all variants.
testDebugUnitTest - Run unit tests for the debug build.
testReleaseUnitTest - Run unit tests for the release build.


在androidstudio开发环境的侧边栏有一个gradle视图


image.png

image.png

列出了所有的task,双击可以运行某个task

BuildConfig

从SDK工具版本升级到17之后,构建工具都会生成一个叫做BuildConfig的类,该类包含一个按照构建类型设置值的DEBUG常量,如果有一部分代码只想在debug版本上运行,比如日志,那么这个常量就会很有用。
我们可以通过Gradle来扩展该文件,这样在debug和release时期就可以拥有不同值的常量。


image.png

例如,我们可以定义一个url(通常debug版和release版的url是不同的)
现在我们自己定义一个变量API_URL

buildTypes {
        release {
            buildConfigField("String","API_URL","\"http://www.miduo.com\"")
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug{

            buildConfigField("String","API_URL","\"http://192.168.3.169\"")
        }
    }

看下buildConfigField这个函数的声明

public void buildConfigField(String type, String name, String value) {
        ClassField alreadyPresent = (ClassField)this.getBuildConfigFields().get(name);
        if(alreadyPresent != null) {
            String message = String.format("BuildType(%s): buildConfigField '%s' value is being replaced: %s -> %s", new Object[]{this.getName(), name, alreadyPresent.getValue(), value});
            this.errorReporter.handleSyncWarning((String)null, 0, message);
        }

        this.addBuildConfigField(new ClassFieldImpl(type, name, value));
    }

查看BuildConfig.java

/**
 * Automatically generated file. DO NOT MODIFY
 */
package com.example.huozhenpeng.myapplication;

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String APPLICATION_ID = "com.example.huozhenpeng.myapplication";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = 1;
  public static final String VERSION_NAME = "1.0";
  // Fields from build type: debug
  public static final String API_URL = "http://192.168.3.169";
}

注意第三个参数的写法,如果写成这样就是错误的

 buildConfigField("String","API_URL","http://192.168.3.169")

看下在BuildConfig中生成的变量


image.png

在BuildConfig中的变量,在java代码中都可以直接使用

package com.example.huozhenpeng.myapplication;

import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        Log.e("tag",BuildConfig.API_URL);
        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState, persistentState);
    }
}

项目范围的设置

如果在你的项目中有多个Andorid module,那么你可以将每个module中通用的构建文件属性提取到顶层构建文件中
例如,在顶层的build.gradle中配置compileSdkVersion属性

allprojects {
    repositories {
        google()
        jcenter()
    }
    android{
        compileSdkVersion 26
    }
}

这样在所有的module中都不再需要配置compileSdkVersion属性了,更好的办法是在顶层构建文件中定义值,然后将它们应用到模块中,我们可以通过ext代码块给build.gradle文件添加额外的属性
在顶层的build.gradle中

ext{
    compileSdkVersion=26
}

在app这个module的build.gradle中

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    defaultConfig {
        applicationId "com.example.huozhenpeng.myapplication"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            buildConfigField("String","API_URL","\"http://www.miduo.com\"")
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug{

            buildConfigField("String","API_URL","\"http://192.168.3.169\"")
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270

推荐阅读更多精彩内容