Android Gradle使用总结(1)

2,675 阅读6分钟

Android Gradle使用篇:

Android Gradle使用总结(1)

Android Gradle使用总结(2)

Gradle是一款优秀的构建系统工具,它的DSL(领域特定语言)基于Groovy实现,可以方便地通过代码控制这些DSL来达到构建的目的。

:执行gradle命令时,默认加载当前目录下的build.gradle文件,亦可以通过-b 指定要加载的执行文件,如: gradlew -b ./app/build.gradle assemble

Gradle常用基础

1、记得使用帮助

(1)查看所有可执行的任务(Tasks)

gradlew tasks

Gradle会以分组的方式列出task列表,比如构建类的 assemable,帮助类的 help等

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

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.
bundleDebug - Creates all Debug bundles.
bundleRelease - Creates all Release bundles.
clean - Deletes the build directory.
cleanBuildCache - Deletes the build cache directory.
compileDebugAndroidTestSources
compileDebugSources
compileDebugUnitTestSources
compileReleaseSources
compileReleaseUnitTestSources

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

Cleanup tasks
-------------
lintFix - Runs lint on all variants and applies any safe suggestions to the source code.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'tapeView'.
components - Displays the components produced by root project 'tapeView'. [incubating]
dependencies - Displays all dependencies declared in root project 'tapeView'.
dependencyInsight - Displays the insight into a specific dependency in root project 'tapeView'.
dependentComponents - Displays the dependent components of components in root project 'tapeView'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'tapeView'. [incubating]
projects - Displays the sub-projects of root project 'tapeView'.
properties - Displays the properties of root project 'tapeView'.
tasks - Displays the tasks runnable from root project 'tapeView' (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.
installRelease - Installs the Release 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.

To see all tasks and more detail, run gradle tasks --all

To see more detail about a task, run gradle help --task <task>

BUILD SUCCESSFUL in 18s
1 actionable task: 1 executed

(2)Gradle Help任务

gradle内置的help任务,可以了解每一个Task的使用帮助,用法是gradlew help --task <taskName> 如:gradlew help --task assemable

2、强制刷新依赖

gradlew --refresh-dependencies assemable

3、多任务执行

只需按顺序以空格分开即可,如gradlew clean jar,先执行clean再执行生成jar

4、自定义属性

自定义属性具有更广泛的作用域,可以跨Project,跨Task访问。只要能访问这些属性所属的对象,那么这些属性就可以被访问到。

apply plugin: "java"

ext.age = 18 //自定义一个属性

//自定义多个属性
ext{
	phone = '020'
	address = ''

	dep = [android : "androidan"] //map
}


sourceSets.all{
	ext.resourcesDir = null
}

sourceSets {
	main{
		resourcesDir="main/res"
	}
	test{
		resourcesDir="test/res"
	}
}

task customProperty{
	doLast{
		println "age: ${age}"
		println "phone: $phone"
		println "address: $address"
		println "android: ${dep.android}"

		sourceSets.each{
			println"${it.name}'s resourcesDir is: ${it.resourcesDir}"
		}
	}
	
}

5、任务的禁用和开启

任务禁用时,当执行到该任务,会skip掉

task task1{
    doLast{
        println 'xxx'
    }
}

task1.enabled = false; //false:禁用,true:开启

6、任务的onlyif 断言

任务有一个onlyIf方法,接收一个闭包作为参数,如果该闭包返回true,则该任务执行,否则跳过

以键值对的形式添加属性:-PK=V,中间不能有空格 ,如:gradle -Pbuild_apps=shoufa build

final String BUILD_APPS_ALL="all";
final String BUILD_APPS_SHOUFA="shoufa";
final String BUILD_APPS_EXCLUDE_SHOUFA="exclude_shoufa";

task QQRelease{
	doLast{
		println "QQRelease"
	}
    
}
task BaiduRelease{
	doLast{
		println "BaiduRelease"
	}
   
}

task build{
	group BasePlugin.BUILD_GROUP
	description '打渠道包'
	dependsOn QQRelease,BaiduRelease
}

QQRelease.onlyIf{
	if (project.hasProperty('build_apps')) {
		Object buildApps = project.property("build_apps")
		if (BUILD_APPS_SHOUFA.equals(buildApps)) {
			return false
		}
	}
	return true;
}

//gradle -Pbuild_apps=shoufa build; //以键值对的形式添加属性:-PK=V,中间不能有空格

7、脚本即代码,代码也是脚本

虽然Gradle是个脚本文件,但写的依旧是代码,Groovy是兼容Java的,能灵活实现很多功能。如,给生成的apk以当前时间命名:

def buildTime(){
    def date = new Date()
    def formattedDate = data.format('yyyyMMdd')
    return formattedDate
}

Groovy基础

1、字符串

单引号和双引号都能定义字符串。区别在于,单引号表示纯粹的字符串常量,而双引号具有运算能力。 如:

def name = "John"
println '单引号${name}' //输出: 单引号${name}
println "双引号${name}"  //输出: 双引号John
println "双引号$name"   //输出: 双引号John

一个美元符号紧接着一对花括号,花括号里放表达式,如${name},当只有一个变量时,可以省略花括号,如$name;

2、集合

(1)List

def nums = [1,2,3,4] //定义arrayList
println nums[1]  //下标索引访问
nums.each{
    println it //forEach,其中it变量为正在迭代的元素
}

(2)Map

def map = ['width':1024,'height':768] //定义map
println map['width'] //访问
println map.height //访问
map.each{
    println "Key:${it.key},Value:$it.value" //forEach,被变量的是Map.Entry
}

(3)方法

  • 括号是可以忽略的
method1(2,3) //
method1 2,3 //可忽略括号,
def method1(int a,int b){
    println a+b
}
  • return 是可以不写的,最后一句代码作为其返回值
def method2(int a,int b){
    if(a>b){
        a //即return a;
    }else {
        b //即return b;
    }
}
  • 代码块/方法是可以作为参数传递的
//呆板写法
nums.each({println it})

//格式化一些
nums.each({
    println it
})

//Groovy中,如果方法的最后一个参数是 闭包,则可以放到方法外面
nums.each(){
    println it
}

//然后省略括号,则变成常见的样式
nums.each{
    println it
}

//多参数调用
eachMap{k,v->
    println "$k is $v"
}
  • JavaBean,可以很容易地访问和修改属性值,而不用通过getter/setter,因Groovy内部已帮我们搞定好。
def Person p = new Person()
println "name is $p.name" //输出null
p.name = "John" 
println "name is $p.name" //输出John

class Person {
    private String name
}
  • 闭包委托 Groovy的闭包有thisObject、owner和delegate三个属性,一般是thisObject>owner>delegate,但可以修改delegate。一般指定delegate为当前it,这样就可以在闭包内对该it进行配置,或调用其方法。
task delegate{
	doLast{
		person{
			name = "cap" //在闭包内对该it进行配置
			age = 20    //在闭包内对该it进行配置
			dumpPersion()  //在闭包内对该it调用其方法
		}
	}


}
def dumpPersion(){
	println "project delegate"
}


class Person{
	private String name
	private int age 

	def dumpPersion(){
		println "name:${name};age:${age}"
	}
}

def person(Closure<Person> closure){
	Person p = new Person()
	closure.delegate = p //设置委托
	closure.setResolveStrategy(Closure.DELEGATE_FIRST)//设置委托优先
	closure(p)
}

Gradle 插件

1、Java Gradle 的sourceSets常用属性

sourceSet,即源代码集合(Android的buildTypes和这个类似),用来描述和管理源代码和资源存放等功能。提供有sourceSets{}闭包放配置和生成sourceSet,如:

sourceSets{
    main{
        //在这里可以对main sourceSet进行配置
        
        java{
            srcDir 'src/java' //更改了java源代码存放目录,默认是 src/main/java
        }
        resources{
            srcDir 'src/resources' //更改了资源文件存放目录,默认是 src/main/resources
        }
    }
    vip{
        //生成了新的 vip sourceSet
    }
}

SourceSet常用属性

属性名 类型 描述
name String 只读,如,main
java SourceDirectorySet 该源集的java源文件
java.srcDirs Set 该源集的java源文件所在目录
resources SourceDirectorySet 该源集的资源文件
resources.srcDirs Set 该源集的资源文件的所在目录
output.classesDir File 该源集编译后的class文件目录
output.resourcesDir File 编译后生成的资源目录
compileClassPath FileCollection 编译该源集时所需的classPath

2、Android Gradle插件分类和三个sourceSet

Android Gradle插件的分类是根据Anroid工程的属性分类的,在Android中,有3类:

  1. App应用工程插件id: com.android.application
  2. Library库工程插件id: com.android.library
  3. Test测试工程插件id: com.android.test

:src目录下的androidTest,main,test分别是3个sourceSet,分别对应,Android单元测试代码,Android app主代码和资源,普通单元测试代码。 在main中,特有AndroidManifest.xml和res这两个Android特有的,用于描述Android App 配置和资源文件。