Gradle Super Detailed Analysis

Keywords: Android Java Gradle cmake

Detailed configuration of android gradle

AppExtension class and its properties

Maybe most people will feel very strange when they see the AppExtension class. In fact, when we fill in the configuration information in build.gradle of app, we often see it. What is it?

If you press ctrl + left mouse button to the android {} and click in, you will know that, in fact, android { } It represents the AppExtension class.

As shown in the picture:

Let's look at AppExtension inheritance:

In addition to AppExtension, there are two similar classes, LibraryExtension and TestExtension.

If the module project is used as a lib, then the android in build. grade under lib corresponds to Library Extension.

Attributes of AppExtension

  • aaptOptions: aapt is a tool that compiles resource files into binary files. aaptOptions represent optional parameters set by the aapt tool.
  • adbExecutable: adb executes from compiling sdk
  • adbOptions: An optional parameter for adb
  • Application Variants: Application Variants List
  • == Build Tools Version=: Build Tools Version (necessary)
  • Build Types: Build types (release and debug in general, and customizable)
  • compileOptions: Compile optional parameters
  • == compileSdkVersion=: Compile sdk version (necessary)
  • Data Binding: Data Binding optional parameter( On the Use of Data Binding)
  • defualtConfig: Default configuration for all packaged projects
  • DefualtPublish Config: The default is release. Use reference
  • dexOptions: Dex optional parameter.
  • External NativeBuild: native compilation support.Reference resources
  • flavorDimensionList:
  • GeneePureSplits: Whether to split into multiple APK s
  • Jacoco: JaCoCo optional parameter
  • lintOptions: Lint Tool Optional Parameters
  • ndkDirectory: ndk directory (generally in local.properties)
  • packagingOptions: Optional parameters for packaging
  • Product Flavors: All flavor s of the project
  • PushNonDefualt: Not just the default publish artifacts. Refer to defualtPublish Config.
  • resourcePrefix: The prefix used when creating a new resource.
  • sdkDirectory: sdk directory (generally in local.properties)
  • Signing Configs: Optional parameters for signature files
  • SorceSets: Resource file directory assignment (Android has its own Android sourceSets, which are commonly used in assets, jin, and other directories)
  • Splits: splits type.
  • testBuildType: Test build type
  • TesOptions: Testing optional parameters
  • testVariants: Test variants
  • Unit Test Variants: Unit Test Variants
  • VaritFilter: Variant Filter

Roughened Closure Representing DSL Language

Such as:

buildTypes { }

AppExtension's approach:
- flavorDimensions (dimensions): Specify the flavor name
- useLibraray(name): Request the use of a lib Library
- useLibrary(name,required): As explained above.

Configration blocks for AppExtension

Like android {} in build.gradle in app, the code is represented by the AppExtension class. The same is true for other configuration closures.

  • aaptOptions{}
The aaptOptions {} code is represented by the AaptOptions class.

Attributes of AaptOptions:
1. Additional Parameters: Additional parameters, List type.
2. Cruncher Enabled: If PNG pictures can be processed quickly in large quantities, boolean type. true means yes.
3. Cruncher Processes: Fast processing may require more memory and CPUs. int type. By default 0, the larger the value, the faster the processing, the larger the memory and CPU required.
4. FailOnMissing ConfigEntry: If no configuration is found, an error is returned. Boolean value, default false.
5. ignoreAssets Pattern: Ignore the Assets module.
6.moCompress: Extension files are not packaged into apk.


Usage (detailed usage may need to see the document):

aaptOptions{
    Cruncher Enabled true//Fast Processing PNG Pictures
}

AaptOptions Official Document

  • adbOption{}
AdbOptions {} corresponds to AdbOptions

Attributes of AdbOptions:
1.installOptions: Optional parameters for apk installation.
2.timeOutInMs: Time out using adb.

Not commonly used
  • buildTypes{}
buildTypes{}The corresponding is BuildType class

buildTypes Properties:

1.applicationIdSuffix: application id Suffix(to Applica)
2.consumerProguardFiles: The obfuscation file is included in the arr In the bag.
3.debuggable: Whether to generate a debug Of apk
4.embedMicroApp: wearable devices app Can you use this compilation type?
5.javaCompileOption: Java Compile configuration parameters
6.jniDebuggable: Can this compiler type be configured with debuggable Of native Code generates a apk
7.manifestPlaceholders: List placeholder
8.minifyEnabled: Is it reduced?
9.multiDexEnabled: Whether to split into multiple Dex
10.multiDexKeepFile: Specifies a text file compiler Dex In file
11.multiDexKeepProguard: Specify a compiler for obfuscated files Dex In file
12.name: build type Name
13.proguardFiles: Confusing files
14.pseudoLocalesEnabled: Whether to generate false scene apk(If no obfuscation rule file is provided, the default obfuscation rule file is set( SDK/tools/proguard/proguard-android.txt))
15.renderscriptDebuggable: Use RenderScript The optimization level of the compiler.
16.shrinkResources: Whether to remove unused resources by default false,Represents no removal.
17.signingConfig: Signature configuration
18.testCoverageEnabled: Test whether coverage is activated.
19.useJack: Obsolete
20.versionNameSuffix: Version name suffix
21.zipAlignEnable: Whether to use zipalign Tool compression.

------------------------------------------------------

buildType Method:

1.buildConfigField(type,name,value): Add a variable generation BuildConfig Class.
2.consumeProguardFile(proguardFile): Add an obfuscated file into arr Bag.
3.consumeProguardFile(proguardFiles): Add obfuscated files into arr Bag.
4.externalNativeBuild(action): Configure local build Options.
5.initWith: Copy this build All attributes of a type.
6.proguardFile(proguardFile): Add a new obfuscation profile.
7.proguradFiles(files):Add new obfuscated files
8.resValue(type,name,value): Add a new generated resource
9.setProguardFiles(proguardFileIterable):Set up an obfuscation profile.


------------------------------------------------------------


buildType Usage:

  buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            shrinkResources true
            zipAlignEnabled true
            debuggable false
            //...
        }

        debug{
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            shrinkResources true
            zipAlignEnabled true
            debuggable true
            //...
        }
    }

BuildType official document

  • compileOptions{}
CompoileOptions {} corresponds to CompileOptions


Properties of CompileOptions:
1.encoding: the encoding format of Java source files
 2.incremental: Should Gradle's new incremental model be written in Java
 3.sourceCompatibility: Specifies the jdk version of the compiled. java file
 4.targetCompatibility: Ensure that the class file is compatible with the target Compatibility specified version, or with the updated java virtual machine


Not very commonly used
  • dataBinding{}
dataBinding{}The corresponding isDataBindingOptions


DataBindingOptionsProperties:

1.addDefualtAdapters: Whether to add a defaultdata binding Adapter. default true. 
2.enabled: Whether to usedata binding
3.version: data binding Use version


dataBindingUse:

dataBinding{
    enabled true
}

Detailed usage of Data Binding

  • defualtConfig{}
defaultConfig{}All flavor They all have common configurations.

//English Interpretation:The default configuration, inherited by all product flavors (if any are defined).


defaultConfig Use:

 defaultConfig {
        applicationId "com.example.zhang.demo"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

If multiple modules are included in the Project, the shared minSdkVersion and targetSdkVersion can be extracted into the build.gradle file in the Project. The next chapter of the details.

  • dexOptions{}
dexOptions{}The corresponding is DexOptions

DexOptions attribute:

1.additionalParameters: to dx Adding a series of additional parameters
2.javaMaxHeapSize: When called dx Time assignment-Xmx Value.
3.jumboMode: Use jumbo(Gigantic)Pattern
4.keepRuntimeAnnotatedClasses: Keep runtime annotations in the main for all classes Dex Medium.
5.maxProcessCount: have access to Dex Maximum number of concurrent processes. Default is4. 
6.optimize: Run in dx Is the compiler available? optimize Mark.
7.preDexLibraries: Whether in advance dex Library, which can improve incremental generation, but clear build It may slow down.
8.threadCount: When dx Number of threads used at runtime. default4One.


dexOptions{}Usage:

dexOptions {
    preDexLibraries  false
    javaMaxHeapSize "4g"
}
  • externalNativeBuild{}
External Native Build {} corresponds to External Native Build

Properties of External NativeBuild:

1.cmake: CMake tool compilation option.
2.ndkBuild: ndk-build option.


There are two modules in externalNativeBuild {}, cmake {} and ndkBuild {} modules.

------------------------------------------------
cmake {} corresponds to CmakeOptions

The attributes of CmakeOption:
1.path: The relative path of your CmakeLists.txt compiler script.

--------------------------------------------------
ndkBuild {} corresponds to NdkBuildOptions

Attributes of NdkBuildOptions:
1.path: The relative path of your Android.mk file.

--------------------------------------------------


Usage of externalNativeBuild {}:

externalNativeBuild{
    ndkBuild{
        path file("src\\main\\jni\\Android.mk")
    }

    cmake {
        path "src/main/cpp/CMakeLists.txt"
    }
}

Android Studio 2.2 Configuration NDK

Android studio 2.2 Compiles NDK with cmake

  • jacoco{}
jacoco {} corresponds to JacocoOptions

Attributes of JacocoOptions:
1.version: outdated

English text:
note: this property is deprecated and will be removed in a future version of the plugin.
  • lintOptions{}
lintOptions{}Corresponding to LintOptions


LintOptions Properties:
1.abortOnError: If an error is found, lint Should the tool exit the program?trueRepresents exit.
2.absolutePaths: Whether or not when the output is wrong, lint The full path should be shown. The default is the relative path, that is, the default.false. 
3.check: Accurate inspection(collect)The set of questions, by default, any problem can be passed LintOptions.getEnable()Enabled, no problem can be passed LintOptions.getDisable()Make it ineffective.
4.checkAllWarnings: Check for all warnings, including those that are turned off by default.
5.disable: adoptid's To suppress this problem and allow modification
6.enable: adoptid's To deal with this problem, step by step, he will addid,And return a collection.
7.explainIssues: Return lint Does it contain an explanation of the error problem?(Be careful: HTML and XML The report will be done unconditionally, ignoring this setting). 
8.htmlOutput: html Output mode.
9.htmlReport: Should we write one? HTML Report, defaulttrue, This usage scenario is LintOptions.getHtmlOutput()Control.
10.ignoreWarings: lint Just check for errors and ignore warnings.
11.lintConfig: The default configuration file serves as a backup.
12.noLines: lint Whether the number of rows is included when the error log is output. defaulttrue. 
13.quiet: lint Should it be quiet(Be quiet). For example: report file writing path, do not write messages.
14.severityOverrides: An optional map of severity overrides. The map maps from issue id's to the corresponding severity to use, which must be "fatal", "error", "warning", or "ignore".
15.showAll: lint Does it contain all the output?
16.textOutput: Text output mode.
17.textReport: Is the text report written by default?false. 
18.warningAsErrors: lint Do you treat warnings as errors?
19.xmlOutput: XML Output mode.
20.xmlReport: XML Write report in format by defaulttrue. 

------------------------------------------------

LintOptions Method:

1.check(id): Check this.idSet of problems
2.check(ids): 
3.disable(id): takeidAdd to the problem set that does not need to be started
4.disable(ids): 
5.enable(id): takeidAdd to the Start Question Set
6.enable(ids)
7.error(id): takeidAdd to the wrong problem set
8.error(ids)
9.fatal(id): takeidadd to fatal Level problem set
10.fatal(ids)
11.ignore(id): takeidadd to ignore Level problem set
12.ignore(ids)
13.waring(id): takeidadd to waring Level problem set
14.waring(ids)

------------------------------------------------

lintOptions{}General usage:

lintOptions {
    abortOnError false
}

Lint Options Official Documents

  • packagingOptions{}
packagingOptions{}The corresponding isPackagingOptions

Packaging options There are three groups of paths: first-picks,merges and excludes:


packagingOptions{}Usage:

packagingOptions {
    pickFirsts = [] // Not really needed because the default is empty.
    merges = []     // Not really needed because the default is empty.
    excludes = []
}

Packaging Options Official Document

  • productFlavors{}
productFlavors{}The corresponding is ProductFlavors

ProductFlavors Properties:

1.applicationId: application program ID. 
2.applicationIdSuffix: application program ID Suffix.
3.consumerProguardFiles: The obfuscation rule file is included aar In the bag.
4.dimension: flavor The size of the name.
5.externalNativeBuild: See you for details. externalNativeBuild{}
6.flavorDeminsion: Obsolete
7.generatedDensities: Obsolete
8.jackOption: jack Configuration options.
9.javaCompileOptions: Java Compile configuration parameters
10.manifestPlaceholders: manifest placeholder
11.multiDexEnabled: Whether to proceed dex split
12.multiDexKeepFile: Text file compiler dex In the document.
13.multiDexKeepProgroud: Text files are compiled as obfuscation rules dex In file
14.ndk: ndk To configure
15.proguardFiles:Confusing files
16.signingConfig: this flavor Signature configuration information of
17.testApplicationId: Test application ID
18.testFunctionalTest: 
19.testHandleProfiling: 
20.testInstrumentationRunner: 
21.testInstrumentionRunnerArguments: 
22.useJack: Obsolete
23.verctorDrawables: Generating Vector Graph Support
24.versionCode: version number
25.versionName:Version name
26.versionNameSuffix: Version name suffix
27.wearAppUnbundled: Whether to wear embedded system app Split mode. Iftrue,Then this app Will be distributed to wearable devices in the application market app. 



productFlavor{}Usage:

productFlavors {

        googlePlay {
        }

        xiaomi {
        }
}
//All Packaging Configurations (Batch Processing Packaging Channel - > manifest Placeholders: Setting Packaging Channels)
productFlavors.all {
    //Platform id
    flavor -> flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name]
}

Official Document of Product Flavor

  • signingConfig{}
signingConfig{}The corresponding is SigningConfig

SigningConfig Properties:

1.keyAlias: Signature use key Alias
2.KeyPassword: Signature used key Password
3.storeFile: store Signature file
4.storePassword: store Signature password
5.storeType: store Signature type
6.v1SigningEnabled: Whether to use jar autograph(Also called v1 autograph). 
7.v2SigningEnabled: Whether to use apk autograph(Also called v2 autograph). 


signingConfig{}Usage:

signingConfigs {
    config {
        keyAlias '...'
        keyPassword '...'
        storeFile file('C:/../Key.jks')
        storePassword '...'
    }
}
  • sourceSets{}
sourceSets{}Corresponding AndroidSourceSet

AndroidSourceSet Properties:

1.aidl: aidl Catalog
2.assets: assets Catalog
3.compileConfiguraName: Compile and configure the resource directory.
4.java: java Code directory (to be compiled).classDocument)
5.jni: jni Resource directory
6.jniLibs: jni Library Directory
7.manifest: AndroidManifest.xml resource file
8.name: source setName.
9.packageConfigurationName: Runtime configured resource set.
10.providedConfigurationName: Only the resource set configured at compile time.
11.renderscript: RenderScript Script resource directory
12.res: Android Resource directory
13.resource: java Resources are copied to output javaresource Catalog


AndroidSourceSet Method:
1.setRoot(path): The root directory of the resource set, where all resources are located.


sourceSets{}Use:

sourceSets {
    //In the main directory
    main {
        //assets directory settings
        assets.srcDirs = ['assets']
        //jni directory settings
        jni.srcDirs 'src/main/jni'
        //jni library settings
        jniLibs.srcDir 'src/main/jniLibs'
    }
}
  • splits{}
splits{}The corresponding is Splites

Splits Properties:

1.abi: ABI Set up
2.abiFilters: Used for multiple apk Of ABI Filter list
3.density: Density setting
4.densityFilters: Used for multiple apk Density filter list
5.language: Language settings.
6.languageFilters: Used for multiple apk Language filter list

-----------------------------------------------------


Spiltes There are three modules. abi{},density{},language{}


abi{}The corresponding is AbiSplitOptions

AbiSplitsOptions Properties:
1.applicableFilters: Returns a list of all applicable filters in this range.
2.enable: Does it split in this range?
3.universalApk: Whether to create all available ABIs One APK. 


AbiSplitesOptions Method:
1.exclude(excludes): Exclude some values.
2.include(include): Contains some values.
3.reset(): ResetsplitTo configure.

----------------------------------------------------------

density{}The corresponding is DensitySplitOptions

DensitySplitOptions Properties:
1.applicableFilters: Returns a list of all applicable filters in this range.
2.auto: Does the compilation system determine partitioning“ language-*"Resources in folders.
3.compatibleScreen: Compatible Screen List
4.enable: Is it split?


DensitySplitOptions Method:
1.exclude(exclude):Exclude some values
2.include(include):Contains some values
3.reset(): ResetsplitTo configure.


-------------------------------------------------------

language{}The corresponding is LanguageSplitOptions

LanguageSplitOptions Properties:
1.enable: Iftrue,That's splitting. language


LanguageSplitOptions Method:
1.include(include): Include a model.


---------------------------------------------------------

splits{}Usage:

splits {
    density {
        enable true
        exclude 'ldpi', 'mdpi'
        compatibleScreens 'normal', 'large', 'xlarge'
    }
} 

//Generate results:
app-hdpi-release.apk
app-universal-release.apk
app-xhdpi-release.apk
app-xxhdpi-release.apk
app-xxxhdpi-release.apk

splits {
    abi {
      enable true
      reset()
      include 'x86', 'armeabi-v7a', 'mips'
      universalApk true
    }
}

//This is to generate app s with different mobile architecture

APK-splite official document

Split Official Documents

Reference articles

  • testOptions{}
testOptions{}The corresponding is TestOptions

TestOptions Properties:
1.reportDir: Report directory
2.resultDir: Result catalog
3.unitTests: Unit test configuration parameters

TestOptions Contain unitTests{}

-------------------------------------------------------

unitTests{}The corresponding is UnitTestOptions

UnitTestOptions Properties:
1.returnDefaultValues: whether unmocked Method from android.jar Throw an exception or default value (0 or null). 


UnitTestOtions Method:
all(configClosure): Configure all unit test tasks.

-------------------------------------------------

testOptions{}Use:

testOptions {
    resultsDir = "$project.buildDir/foo/results"
}

Reference document

AppExtension document

Gradle translation

        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/markdown_views-ea0013b516.css" />
            </div>

Posted by livvylove on Fri, 17 May 2019 05:09:12 -0700