The quieter the heart, the quieter the night

I want to share some knowledge about gradle. Some structure is slightly confused, but it does not affect reading.

Gradle is a build tool that builds, runs, signs, packages, and manages dependencies on Java. It was originally designed to support Java

AS the root directory of the project. A build gradle file, including the classpath ‘com. Android. View the build: gradle: 2.1.2’ is used to rely on gradle plug-in code, ps: the final version is not gradle version, It’s defined by Google

Gradle projects and Tasks

The two most important concepts in grade are project and Tasks. Every build is completed by at least one project, so project in Android Studio and Project in Gradle are not the same concept. Each project has at least one task. Each build.grade file represents a project. Tasks are defined in build.gradle. When initializing the build process, Gradle assembles all projects and tasks based on the build file. A task contains a sequence of actions that are then executed in sequence. An action is a piece of code that is executed, much like a Java method.

Build life cycle

Once a task is executed, it is not executed again. Tasks that do not contain dependencies are always executed first. A build will go through the following three phases:

Initialization phase: The project instance is created here. If there are multiple modules, i.e. multiple build.gradle files, multiple projects will be created.

Configuration phase: In this phase, the build.gradle script is executed to create and configure all tasks for each project.

Execution stage: At this stage, Gradle determines which tasks will be executed and which tasks will be executed depending on the parameters passed at the start of the build and the location of the current folder.

The project structure

Gradle uses a concept called source set. A source set is a set of resource files that will be compiled and executed. For Android projects, main is a source set. To write test cases, you need to open another source set. Called androidTest so you can compile and execute test cases separately.

The module of the build. Gradle

 apply plugin: 'com.android.application'
   android {
           compileSdkVersion 22
           buildToolsVersion "22.0.1"
           defaultConfig {
               applicationId "com.gradleforandroid.gettingstarted"
               minSdkVersion 14
               targetSdkVersion 22
               versionCode 1
               versionName "1.0"
           }
           buildTypes {
               release {
                   minifyEnabled false
                   proguardFiles getDefaultProguardFile
                    ('proguard-android.txt'), 'proguard-rules.pro'
               }
        } 
    }
    dependencies {
           compile fileTree(dir: 'libs'.include: ['*.jar'])
           compile 'com. Android. Support: appcompat - v7:22.2.0'
     }Copy the code

Global configuration

1. Create the config.gradle file in the root directory of the project

ext {
    android = [
        compileSdkVersion: 23,
        buildToolsVersion: "23.0.2",
        minSdkVersion: 14,
        targetSdkVersion : 22,
       ]
    dependencies = [
            appcompatV7':'com.android.support:appcompat-v7:23.2.1', design : 'com.android.support:design:23.2.1']}Copy the code

2. Under build.gradle of the project

// Reference the configuration file
`apply from:"config.gradle"`Copy the code

3. Use build.gradle in app

android {
    compileSdkVersion rootProject.ext.android.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion
    defaultConfig {
        applicationId "com.wuxiaolong.gradle4android"
        minSdkVersion rootProject.ext.android.minSdkVersion
        targetSdkVersion rootProject.ext.android.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }


dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit: junit: 4.12'
    compile rootProject.ext.dependencies.appcompatV7
    compile rootProject.ext.dependencies.design
}Copy the code

Gradle Wrapper

Gradle Wrapper is a Wrapper that manages Gradle and assigns Gradle to different projects so that all projects can work properly.

Gradle Wrapper for each executable script, bat for Windows, shell for MAC. When your project starts, the corresponding script will start. Download the gradle version. The gradle download is stored in the appropriate configuration file, Properties, as shown below

├─ Heavy Exercises ─ Heavy Exercises ─ Heavy Exercises ─ heavy Exercises ─ heavy Exercises ─ heavy Exercises ─ heavy Exercises ─ heavy ExercisespropertiesCopy the code

Gradle common commands

Gradlew -v Displays the gradle version used for the current project

Gradlew clean the build folder in the app directory

Gradlew Build checks dependencies and builds packages (formal and test)

Gradlew assembleDebug compiles and prints Debug packages

Gradlew assembleRelease compiles and releases the package

Gradle Tasks Lists all tasks(executable tasks)

Gradlew androidDependencies lists all dependency files

The gradle under the Android

Android Studio will generate three gradle files when we create the project, two build.gradle files and one setting.gradle file

setting.gradle

include ':app'Copy the code

Gradle file is executed during initialization to generate the corresponding project. The project will generate a series of tasks according to the corresponding build.gradle file. These tasks are the code that gets executed.

Gradle is designed to operate on multiple modules. For single modules, gradle is not very useful.

Build. gradle in the root directory

This gradle file is the default configuration that defines the common properties of modules under the project

buildscript {
    // Define the source of the dependency package
     repositories {
         jcenter() 
     }
    // Define the plug-ins that the build process depends on
    // For example, when using Dagger2, you need to add another apt plugin here
      dependencies {
          classpath 'com.android.tools.build:gradle:1.23.'}}// Define the properties of each module. You can add any tasks, that is, the build.gradle file, under AllProjects, is the main place to do it
allprojects {
     repositories {
          jcenter() 
     }
}Copy the code

Build. gradle in the module

Gradle files in a module only apply to that module and override properties passed from gradle in the root directory. The default structure

// A plugin written by the Google team that provides building, packaging and testing of Android applications and dependent libraries
apply plugin: 'com.android.application'

   android {
       compileSdkVersion 22
       buildToolsVersion "22.0.1"
       defaultConfig {
           applicationId "com.gradleforandroid.gettingstarted"
           minSdkVersion 14
           targetSdkVersion 22
           versionCode 1
           versionName "1.0"
       }
       buildTypes {
           release {
               minifyEnabled false
               proguardFiles getDefaultProguardFile
                ('proguard-android.txt'), 'proguard-rules.pro'
           }
        } 
    }
    dependencies {
       compile fileTree(dir: 'libs'.include: ['*.jar'])
       compile 'com. Android. Support: appcompat - v7:22.2.0'
     }Copy the code

The required properties for Android are compileSdkVersion and buildToolsVersion

CompileSdkVersion: API version you want to use when compiling this app. BuildToolsVersion: Version number of the build tool.

The build tool contains many useful command line commands, such as aapt,zipalign,dx, etc., which can be used to generate a wide variety of applications. You can download these build tools through the SDK Manager.

The defaultConfig method contains the core properties of the app, which are overridden by the corresponding properties in androidmanifest.xml.

defaultConfig {
   The packagename is used as the packagename and R file's packagename. The applicationId is used as a unique identifier for different devices and various application markets.
   applicationId "com.gradleforandroid.gettingstarted"
   minSdkVersion 14
   targetSdkVersion 22
    // Version id
   versionCode 1
    // It doesn't work
   versionName "1.0"
}Copy the code

Dependency management

Gradle dependency management is very useful. With a single line of code, Gradle will pull the jars you need from a remote repository.

A repository here is usually a remote repository, such as Jcenter,Maven, etc. A repository is a collection of JAR files. Once you define what JAR files you need, Gradle will pull the JAR files from your repository. Jar files are pulled from remote repositories when you perform a build, and the cache is kept locally, so a version of the dependencies only needs to be downloaded once.

Defining a dependency usually requires three elements: the name of the organization that created the library, and usually the package name. Name is the library’s unique identifier. Version is the library’s version number

Regular writing

dependencies {
   compile 'com. Google. Code. Gson: gson: 2.3'
   compile 'com. Squareup. Retrofit: retrofit: 1.9.0'
}Copy the code

Finished writing

dependencies {
  compile group: 'com.google.code.gson', name: 'gson', version:'2.3'
  compile group: 'com.squareup.retrofit', name: 'retrofit'
       version: '1.9.0'
 }Copy the code

Of course, there are some libraries that are not in Maven or JCenter, so you can define them by writing urls in Maven

repositories {
       maven {
           url "http://repo.acmecorp.com/maven2"}}Copy the code

Relying on local

Add jar files as dependencies

dependencies {
   compile files('libs/libraryname.jar')}Copy the code

All jar packages in libs directory

dependencies {
   compile fileTree('libs')
 }
或者
dependencies {
   compile fileTree(dir: 'libs', include: ['*.jar'])}Copy the code

Native packages (Libraries written in C/C ++ will be called so packages)

Create a jniLibs dependencies {compile fileTree(dir: ‘jniLibs’, include: [‘* so’])}

Arr files (dependencies containing resource files)

Change the configuration of build.gradle in app to

apply plugin: 'com.android.library'
/ / delete
applicationId "com.***"Copy the code

Outputs the AAR package in build/outputs/ AAR

The aar file is also a JAR, so it can also be placed in the libs directory, and then in the Android method in build.gradle

repositories {  
    flatDir {  
    dirs 'libs'  
}Copy the code

Under the Dependencies method

compile(name:'libraryname', ext:'aar')Copy the code

This means that in the libs directory, there is a file called LibraryName with the suffix AAR

Form of dependence

 compile 'com. Google. Code. Gson: gson: 2.3'Copy the code

This is the way we normally use it, complie: contains all dependencies, both in Debug mode and in Release mode and so on

Provided: means debug support is provided, but release is not written. TestCompile and androidTestCompile: Mainly used for tests

There are also debugCompile and releaseProvided modes that can be configured

Different dependency modes need to be configured in different situations

I’m just a bit of a newbie on the Android development road. If any of you find anything wrong in this article, please help me point it out. Your criticism and encouragement are my motivation.