Gradle other modules

A, Settings

Settings. gradle (settings. Java) determines which projects need to be processed by Gradle and takes up about one-third of gradle’s life cycle, the Initialzation phase.

Second, SourceSet class

Change the default file location so that Gradle knows which resources to look for in which folders.

// sourceSets can be called multiple times
android {
    sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }
    sourceSets {
        main {
            res.srcDirs = ['src/main/res'.'src/main/res-ad'.'src/main/res-player']}}}// sourceSets is usually a one-time configuration
android {
    sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
            res.srcDirs = ['src/main/res'.'src/main/res-ad'.'src/main/res-player']}}}// Configure sourceSets using a programming philosophy
this.android.sourceSets{
    main {
        jniLibs.srcDirs = ['libs']
        res.srcDirs = ['src/main/res'.'src/main/res-ad'.'src/main/res-player']}}Copy the code

Gradle Plugin

What is a Gradle Plugin

Plugin in Gradle is the embodiment of Task encapsulation to complete a specified function. As long as the project depends on a Plugin, it can execute all functions of the Plugin. For example, using Java plug-in, you can print jar package, and using Android plug-in, you can generate APK and AAR.

2. Custom Plugin

1. Create the plug-in project

  1. Create the buildSrc folder in the project directory.
  2. In the buildSrc directory, create the SRC folder, build. Gradle file.
  3. In the buildSrc/ SRC directory, create the main folder.
  4. Under buildSrc/ SRC /main, create groovy and Resources folders, respectively.
  5. In buildSrc/SRC/main/resources to create a meta-inf folder, create a gradle again under the meta-inf – plugins folder.
  6. Enter the following script in the build.gradel file:
apply plugin: 'groovy'

sourceSets {
    main {
        groovy {
            srcDir 'src/main/groovy'
        }
        resources {
            srcDir 'src/main/resources'}}}Copy the code

Finally, Async projects and buildSrc is identified, as shown in the following figure:

2. Create a plug-in class

Like Java, in groovy directory, create a package, create a plug-in class (such as: com. LQR. Gradle. Study. GradleStudyPlugin), the plug-in class must implement the Plugin interface.

Note: Gradle plug-in classes are.groovy files, not.java files

import org.gradle.api.Plugin
import org.gradle.api.Project

/** * Custom Gradle plugin */
class GradleStudyPlugin implements Plugin<Project> {

    /** * The method to execute when the plug-in is introduced *@paramProject introduces the project */ of the current plug-in
    @Override
    void apply(Project project) {
        println 'hello gradle study plugin. current project name is ' + project.name
    }
}
Copy the code

3. Specify the plug-in entry

After writing the logic for the plug-in class, you need to create a properties file in the meta-info.gradle-plugins directory. Com. LQR. Gradle. Study. The properties), the in the plug-in class declaration in the properties, in order to specify the plugin entrance.

The name of the properties file will be used as the basis for the current Gradle plug-in to be referenced by the APP project.

implementation-class=com.lqr.gradle.study.GradleStudyPlugin// If an error is reportedCould not find implementation class 'xxxThe default package does not need to write the package path. Change the package path as follows: //implementation-class=GradleStudyPlugin
Copy the code

4. Use custom plug-ins

Open the app project build.gradle, apply the custom Gradle plugin, and Async.

apply plugin: 'com.android.application'
apply plugin: 'com.lqr.gradle.study'

android {
  ...
}
Copy the code

As you can see, during the gradle configuration phase, the logs from the apply method of the previous custom plug-in are printed.

5. Create extended attributes

In Android {}, you can configure parameters such as compileSdkVersion. Essentially, you create a javaBean in gradle script closure and pass it to your plug-in for reading. The steps are as follows:

1) Create an entity class and declare member variables that receive parameters configured in Gradle. (This can be interpreted as a javaBean, but note that the file suffix is.groovy, not.java.)

class ReleaseInfoExtension {
    String versionCode
    String versionName
    String versionInfo
    String fileName

    ReleaseInfoExtension() {}

    @Override
    String toString() {
        return "versionCode = ${versionCode} , versionName = ${versionName} ," +
                " versionInfo = ${versionInfo} , fileName = ${fileName}"}}Copy the code

2) In the custom plug-in, extend the current project.

class GradleStudyPlugin implements Plugin<Project> {

    /** * The method to execute when the plug-in is introduced *@paramProject introduces the project */ of the current plug-in
    @Override
    void apply(Project project) {
        // A releaseInfo extension can be initialized using a releaseInfo closure in a Gradle script.
        project.extensions.create("releaseInfo", ReleaseInfoExtension)
    }
}
Copy the code

3) Open build.gradle in the app project and configure the specified parameters by extending the named closure of the key value.

apply plugin: 'com.lqr.gradle.study'

releaseInfo {
    versionCode = '1.0.0'
    versionName = '100'
    versionInfo = 'First app message'
    fileName = 'release.xml'
}
Copy the code

4) Receiving parameters, such as:

def versionCodeMsg = project.extensions.releaseInfo.versionCode
Copy the code

6. Create an extended Task

A custom plug-in encapsulates some common tasks, so extending tasks is the most important part of a custom plug-in.

Write the app version information to an XML file. Write the app version information to an XML file.

import groovy.xml.MarkupBuilder
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction

class ReleaseInfoTask extends DefaultTask {

    ReleaseInfoTask() {
        group 'lqr' // Specify a group
        description 'update the release info' // Add description information
    }

    /** * The TaskAction annotation allows methods to be executed during gradle execution. * doFirst is actually doing things externally@TaskActionAdd execution logic to the front of the. * doLast is external for@TaskActionAdd the execution logic at the end of the. * /
    @TaskAction
    void doAction() {
        updateInfo()
    }

    private void updateInfo() {
        // Get the parameters configured in the Gradle script
        def versionCodeMsg = project.extensions.releaseInfo.versionCode
        def versionNameMsg = project.extensions.releaseInfo.versionName
        def versionInfoMsg = project.extensions.releaseInfo.versionInfo
        def fileName = project.extensions.releaseInfo.fileName
        // Create an XML file
        def file = project.file(fileName)
        if(file ! =null && !file.exists()) {
            file.createNewFile()
        }
        // Create the classes needed to write the XML data.
        def sw = new StringWriter();
        def xmlBuilder = new MarkupBuilder(sw)
        // If there is no content in the XML file, create one more realEase node and write the XML data
        if(file.text ! =null && file.text.size() <= 0) {
            xmlBuilder.releases {
                release {
                    versionCode(versionCodeMsg)
                    versionName(versionNameMsg)
                    versionInfo(versionInfoMsg)
                }
            }
            file.withWriter { writer ->
                writer.append(sw.toString())
            }
        } else { // If there is already content in the XML file, append it to the original content.
            xmlBuilder.release {
                versionCode(versionCodeMsg)
                versionName(versionNameMsg)
                versionInfo(versionInfoMsg)
            }
            def lines = file.readLines()
            def lengths = lines.size() - 1
            file.withWriter { writer ->
                lines.eachWithIndex { String line, int index ->
                    if(index ! = lengths) { writer.append(line +'\r\n')}else if (index == lengths) {
                        writer.append(sw.toString() + '\r\n')
                        writer.append(line + '\r\n')}}}}}}Copy the code

Like creating extended properties, extending Tasks requires creating injections in project.

/** * Custom Gradle plugin */
class GradleStudyPlugin implements Plugin<Project> {

    /** * The method to execute when the plug-in is introduced *@paramProject introduces the project */ of the current plug-in
    @Override
    void apply(Project project) {
        // Create extended attributes
        // A releaseInfo extension can be initialized using a releaseInfo closure in a Gradle script.
        project.extensions.create("releaseInfo", ReleaseInfoExtension)
        / / create a Task
        project.tasks.create("updateReleaseInfo", ReleaseInfoTask)
    }
}
Copy the code

After Async project again, you can see the custom Task in the Gradle tag of Idea.

This is the core of a custom Gradle plugin. However, this plugin is visible only to the current project, so if we want to use our custom Grdle plugin for other projects, we need to create a separate library project. Create all the files in the buildSrc directory and upload them to the Maven repository.

Android plugin for Gradle extension

The translator sequence | Gradle Android plugin user guide translation

Manipulation tasks (task) | Gradle Android plugin user guide translation

Custom Apk output position:

this.afterEvaluate {
  this.android.applicationVariants.all { variant ->
    def output = variant.outpus.first() Outputs is a collection, but only one element, that is, the output apk's file.
    def apkName = "app-${variant.baseName}-${variant.versionName}.apk"
    output.outputFile = new File(output.outputFile.parent, apkName)
  }
}
Copy the code

variant.baseName : baidu-release variant.name : baiduRelease