Android Gradle

Android Gradle

Android Gradle

Gradle is an excellent build system tool. Its DSLS (Domain-specific languages) are implemented in Groovy and can be easily controlled by code for building purposes.

Note: Gradle command builds. Gradle file in the current directory by default. You can also specify an executable file to load by using -b, for example, gradlew -b./app/build.gradle assemble

Gradle is a common foundation

1. Remember to use help

(1) View all available Tasks (Tasks)

gradlew tasks

Gradle lists tasks in groups, such as assemable for build classes, help for help classes, and so on

------------------------------------------------------------
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 inthis 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 thesource 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 forthe Debug build. uninstallRelease - Uninstalls the Release build. Verification tasks ------------------ check - Runs all  checks. connectedAndroidTest - Installs and runs instrumentation testsfor 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
Copy the code

(2) Gradle Help task

Gradlew help — Task

gradlew help — Task assemable

2. Force to flush dependencies

gradlew --refresh-dependencies assemable

3. Multitasking

Just separate them in order with Spaces, for example, gradlew clean jar, clean first and then generate jar

4. Customize attributes

Custom properties have wider scope and can be accessed across projects and tasks. Properties can be accessed as long as the object they belong to is accessible.

apply plugin: "java"

ext.age = 18 // Define an attribute

// Customize multiple attributes
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}"}}}Copy the code

5. Disable and enable tasks

If a task is disabled, the task will be skipped when it is executed

task task1{
    doLast{
        println 'xxx'
    }
}

task1.enabled = false; //false: disable,trueOpen:Copy the code

The onlyif assertion of the task

The task has a onlyIf method that accepts a closure as an argument and executes if the closure returns true, otherwise the task is skipped

Add attributes as key-value pairs: -pk =V without Spaces in between, for example: 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 'Channel package'
	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; // Add attributes as key-value pairs: -pk =V without Spaces
Copy the code

Script is code, code is script

Gradle is a script file, but it still writes code. Groovy is Java compliant and has a lot of flexibility. For example, name the generated APK with the current time:

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

Groovy based

1. String

Both single and double quotes define strings. The difference is that single quotes represent pure string constants, whereas double quotes have computational power. Such as:

def name = "John"
println 'Single quote ${name}' // Output: single quote ${name}
println "${name}"  // Output: double quotes John
println $name = $name   // Output: double quotes John
Copy the code

A dollar sign is followed by a pair of curly braces containing expressions such as ${name}. If there is only one variable, the curly braces can be omitted, such as $name.

2, collections,

(1) the List

def nums = [1.2.3.4] / / define the arrayList
println nums[1]  // subscript index access
nums.each{
    println it //forEach, where the it variable is the element being iterated
}
Copy the code

(2) the Map

def map = ['width':1024.'height':768] / / define the map
println map['width'] / / access
println map.height / / access
map.each{
    println "Key:${it.key},Value:$it.value" //forEach, the variable is map.entry
}
Copy the code

(3) Methods

  • The parentheses are negligible
method1(2.3) //
method1 2.3 // Omit parentheses,
def method1(int a,int b){
    println a+b
}
Copy the code
  • Return can be omitted, with the last line as its return value
def method2(int a,int b){
    if(a > b) {a / / thatreturn a;
    }else{b / / that isreturnb; }}Copy the code
  • Blocks/methods can be passed as arguments
//
nums.each({println it})

// Format some
nums.each({
    println it
})

// In Groovy, if the last argument to a method is a closure, it can be placed outside the method
nums.each(){
    println it
}

// Then omit the parentheses to return to the usual style
nums.each{
    println it
}

// multi-parameter call
eachMap{k,v->
    println "$k is $v"
}
Copy the code
  • Javabeans, which make it easy to access and modify property values without going through getters/setters, because Groovy takes care of that for us internally.
def Person p = new Person()
println "name is $p.name"// output null p.name ="John" 
println "name is $p.name"Person {private String name}Copy the code
  • Groovy’s closures have thisObject, Owner, and Delegate properties, which are usually thisObject> Owner > Delegate, but the delegate can be modified. The delegate is typically specified as the current IT so that the IT can be configured within the closure or its methods can be called.
task delegate{
	doLast{
		person{
			name = "cap" // Configure the IT in the closure
			age = 20    // Configure the IT in the closure
			dumpPersion()  // Call its methods on the IT within the closure}}}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 // Set the delegate
	closure.setResolveStrategy(Closure.DELEGATE_FIRST)// Set delegate priority
	closure(p)
}
Copy the code

Gradle plug-in

Java Gradle sourceSets common property

SourceSet, or collection of source code (Android buildTypes is similar to this), describes and manages functions such as source code and resource repositories. SourceSets {} closures are provided to put configuration and generate sourceSet, such as:

sourceSets{main{// Here we can set mainsourceSet to configure Java {srcDir'src/java'SRC /main/ Java} resources{srcDir} SRC /main/ Java} resources{srcDir'src/resources'SRC /main/resources}} VIP {// new VIP is generatedsourceSet
    }
}
Copy the code

SourceSet Common attributes:

The property name type describe
name String Read-only, for example, main
java SourceDirectorySet The Java source file for the source set
java.srcDirs Set The directory where the Java source files for this source set are located
resources SourceDirectorySet The resource file for this source set
resources.srcDirs Set The directory where the resource files for this source set reside
output.classesDir File The compiled class file directory of the source set
output.resourcesDir File Directory of resources generated after compilation
compileClassPath FileCollection The classPath required to compile the source set

Android Gradle plugin classification and three sourceSet

Android Gradle plugin is classified according to the attributes of Android project. In Android, there are three types:

  1. App Application engineering plug-in ID: com.android.application
  2. Library Library project plugin ID: com.android.library
  3. Test Test project plug-in ID: com.android. Test

Note: SRC directory androidTest, main, test are 3 sourceSet respectively, corresponding to Android unit test code, Android app main code and resources, common unit test code. In main, androidmanifest.xml and res are unique to Android and are used to describe Android App configuration and resource files.