directory

DefaultConfig 1, find out some questions 2, defaultConfig exist form 3, defaultConfig attribute meaning 4, defaultConfig method meaning 3, write last

One, foreword

In android development, gradle is responsible for compiling. But many times when we go into the build.gradle file, we feel like we don’t know what we’re doing, so kids summarize and share what they’ve learned.

Without further ado, today we are sharing the Android defaultConfig property in our build.gradle file for each module (application level)

Second, the defaultConfig

1. Clarify a few issues

Before we share defaultConfig, we need to clear up a few questions that have been bothering our children, so let’s record and share them.

(1) What form does build. Gradle finally exist in? (2) Why does the build.gradle file under each module have a line of apply plugin: ‘com.android.library’ at the beginning?

The automatically generated build.gradle format is shown below

apply plugin: 'com.android.library'

android {
	// Omit some configurations
}

dependencies {
	// omit dependencies
}
Copy the code

This file will eventually be converted toorg.gradle.api.ProjectClass (whose class relationships are shown below).

  • The first line of codeapplyWill be calledPluginAwarevoid apply(Map<String, ? > options);Method to set the plug-in;
  • The followingandroid, is not in Gradle,It’s the first line of code the plug-in brings in. It’s going to map to thetacom.android.build.gradle.AppExtensionClass;
  • The last of thedependenciesTo callProjectvoid dependencies(Closure configureClosure);Methods;

2. Existence form of defaultConfig

DefaultConfig is mapped to the defaultConfig class, whose inheritance structure is shown below

3. Meaning of attributes in defaultConfig

The following is the official documentation, which will be explained in version 3.3. Other versions may have minor changes.

DefaultConfig Official document portal

3.1 applicationId

  • Type: String
  • Description: The id of the application, known as the package name. We all know that Android Studio uses the applicationId as the package name, except when we used Eclipse.
  • Usage:
defaultConfig {
    // applicationId Specifies the package name of the application
    // applicationId replaces the value of the package under the manifest tag in androidmanifest.xml
    applicationId "com.zinc.gradlestudy". Omit other configurations}Copy the code

3.2 applicationIdSuffix

  • Type: String
  • Description: Appends to the applicationId string above to form the final package name.
  • Usage:
defaultConfig {
	/ / if the applicationId is com. Any zinc. Gradlestudy, eventually will form a com. Any zinc. Gradlestudy. Debug package name
    applicationIdSuffix "debug". Omit other configurations}Copy the code

3.3 externalNativeBuild

  • Type: ExternalNativeBuildOptions
  • Here we set some parameters for the NDK compilation process. It can be divided into cmake and ndkBuild parameters.
  • Usage:
defaultConfig {
    externalNativeBuild {
        ndkBuild {
            // Passes an optional argument to ndk-build.
            arguments "NDK_MODULE_PATH+=.. /.. /third_party/modules"
        }
        // For ndk-build, instead use the ndkBuild block.
        cmake {
             // Passes optional arguments to CMake.
             arguments "-DANDROID_ARM_NEON=TRUE"."-DANDROID_TOOLCHAIN=clang"

             // Sets a flag to enable format macro constants for the C compiler.
             cFlags "-D__STDC_FORMAT_MACROS"

             // Sets optional flags for the C++ compiler.
             cppFlags "-fexceptions"."-frtti"

             // Specifies the library and executable targets from your CMake project
             // that Gradle should build.
             targets "libexample-one"."my-executible-demo"}}}Copy the code

Cmake Specific parameter portal ndkBuild Specific parameter portal

3.4 dimension

  • Type: String
  • Description: The current configuration belongs to the “flavor dimension”, this parameter has no practical significance, in the multi-channel package, there will be more sharing.
  • Usage:
defaultConfig {
	dimension 'debug'. Omit other configurations}Copy the code

3.5 consumerProguardFiles

  • Type: List< File >
  • Description: This property only applies to those we createdlibraryThis includes libraries that we import as AArs or create directly. What it does is,Is responsible for obfuscation rules when the library is compiled, we can no longer manage the obfuscation rules of each library under the module of the main App, and can directly use the obfuscation rule files of each library.
  • Usage:
defaultConfig {
	consumerProguardFiles 'consumer-rules.pro'. Omit other configurations}// Since this attribute is of type List
      
       , if multiple File configurations are required, it is shown below
      
defaultConfig {
	consumerProguardFiles 'consumer-rules.pro'.'zincPower-rules.pro'. Omit other configurations}Copy the code

3.6 javaCompileOptions

  • Type: JavaCompileOptions
  • Description: Configures some parameters of Java at compile time, such as the ones we useannotationProcessorIs required.
  • Usage:
defaultConfig {
	javaCompileOptions {
        annotationProcessorOptions{
			arguments = []
			classNames ' '. }}... Omit other configurations}Copy the code

JavaCompileOptions Specifies parameters that can be configured. Please enter the portal

3.7 manifestPlaceholders

  • Type: Map
    ,>
  • Description: Configuration is available inAndroidManifest.xmlThe parameter replaced in defaultConfig is generally used in multi-channel and will not be used in defaultConfig.
  • Usage:

To configure the logo for our application, we can use the following section in Gradle

defaultConfig {
	manifestPlaceholders = [APP_LOGO_ICON: "@mipmap/ic_logo"]}Copy the code

Then use it in androidmanifest.xml, using ${the name of the variable you configured}

// To use replacement in the application, add the tools:replace tag and write the name we need to replace, such as android:icon here<application
    android:allowBackup="true"
    android:icon="${APP_LOGO_ICON}"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:replace="android:icon">.Copy the code

3.8 multiDexEnabled

64K reference restriction issue official document portal

  • Types: Boolean
  • Description: Whether subcontracting is enabled. Because the method index value in Android is a two-byte, four-digit hexadecimal value, namely [0, 0xFFFF], the maximum number of methods is 65536. Once we exceed that, we need to subcontract, so we need to turn this parameter on.
  • Usage:
defaultConfig {
	multiDexEnabled true. }// Add dependencies
dependencies {
	// If you are using AndroidX, use the following import
	/ / implementation 'androidx. Multidex: multidex: 2.0.1'
	// If you are not using AndroidX, use the following paragraph
    compile 'com. Android. Support: multidex: 1.0.3'
}
Copy the code

There are two ways to start MultiDex:

// Make your Application inherit from MultiDexApplication.
public class MyApplication extends MultiDexApplication {}// Second: override the Application method attachBaseContext
public class MyApplication extends Application {

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this); }}Copy the code

Finally, don’t forget to use our Application above in androidmanifest.xml.

3.9 multiDexKeepFile

  • Type: the File
  • Description: Package the classes we need into the main package, i.eclasss.dex. We shared in point 3.8 that we use multi-package processing, and sometimes we need to pack some major classes into the main package, so we can use this property.
  • Usage:
defaultConfig {
	multiDexKeepFile file('multidex-config.txt')... }Copy the code

In multidex-config. TXT, each file contains one line

com/example/MyClass.class
com/example/TestClass.class
Copy the code

3.10 multiDexKeepProguard

  • Type: the File
  • Description: Package the classes we need into the main package, the same function as in point 3.9, the difference is written.
  • Usage:
defaultConfig {
	multiDexKeepFile file('multidex-config.pro')... }Copy the code

Multidex-config. pro is written as follows

Com.example package -keep class com.example.** {*; }Copy the code

3.11 the NDK

  • Type: NdkOptions
  • Description: Used for ABI filtering
  • Usage:

With the following configuration, the compiled Apk package contains only Armeabi-v7A and does not contain other schemas, such as “X86”.

defaultConfig {
	// There is currently only one attribute in NDK, abiFilter, so NDK is currently only used for abi filtering
	ndk {
        abiFilter 'armeabi-v7a'}... }Copy the code

For details about the NdkOptions parameters, see the official document Portal

3.12 proguardFiles

  • Type: List
  • Description: Configures the obfuscation rule file, but we generally do not use this configuration here, but inbuildTypesIn the combinationminifyEnabledUse together.

3.12 signingConfig

  • Type: SigningConfig
  • Description: Configure signature configuration, but not in this case, but in buildTypes, which won’t be explained here.

3.13 vectorDrawables

  • Type: VectorDrawablesOptions
  • Description: Configures the parameters of the vector diagram
  • Usage:

VectorDrawablesOptions has only two parameters, generateddimension and useSupportLibrary. The usefulness of the distinction is as follows

defaultConfig {
    vectorDrawables {
        // If minSdkVersion is less than 21, only PNG of mdpi is generated
        generatedDensities 'mdpi'

        // Set to true, generateddimension is ignored, SVG compatible bundle is added, and PNG is not generated
        useSupportLibrary true}}Copy the code

Vector graph usage, you can see another piece of children’s article

3.14 versionCode

  • Type: an Integer
  • Description: Apply the current version value. andversionNameIn the eyes of children,versionCodeIt’s for programmers,versionNameIt’s for product managers and users.
  • Usage:
defaultConfig {
    versionCode 1000. }Copy the code

3.15 versionName

  • Type: String
  • Description: Application version. The version of the application we usually say is “1.2.0” is configured by this value.
  • Usage:
defaultConfig {
	versionName "1.0.0". }Copy the code

3.16 versionNameSuffix

  • Type: String
  • Description: Append the suffix to the 3.15 subdot “version”
  • Usage:
defaultConfig {
	// If versionName is "1.0.0", the final version is named 1.0.0.test
	versionNameSuffix ".test". }Copy the code

4. Meaning of methods in defaultConfig

4.1 buildConfigField (type, name, value)

  • Description: We can add values to the BuildConfig class, which will eventually add the following line of code to BuildConfig.
// The value of a value is left as is
<type> <name> = <value>
Copy the code
  • Usage:
defaultConfig {
    // This can be obtained by BuildConfig
    buildConfigField('String'.'name'.'"zinc"')
    buildConfigField('int'.'age'.'26')... }Copy the code

This results in the configuration shown below, which we can obtain with the following code

String name = BuildConfig.name;
int age = BuildConfig.age;
Copy the code

The value of theta is thetaWhen we set parameters of type String, we need to enclose “” in quotes (as in the example for the name attribute). Remember that!

4.2 consumerProguardFile (proguardFile)

  • Description: The same effect as the 3.5-dot property consumerProguardFiles shared above. Only one obfuscation file can be set here.
  • Usage:
defaultConfig {
	consumerProguardFile('consumer-rules.pro')}Copy the code

4.3 consumerProguardFiles (proguardFiles)

  • Description: The 3.5-dot property consumerProguardFiles has the same effect as the one shared above, but is also multiple obfuscation files.
  • Usage:
defaultConfig {
	consumerProguardFiles('consumer-rules.pro'.'zincPower-rules.pro',...). }Copy the code

4.4 maxSdkVersion (maxSdkVersion)

  • Description: Set the highest supported version of the app
  • Usage:
defaultConfig {
	// Supports up to version 28
	maxSdkVersion 28
}
Copy the code

4.5 minSdkVersion (minSdkVersion)

  • Description: Set the lowest supported version of the application
  • Usage:
defaultConfig {
	// The minimum version is 19
	minSdkVersion 19
}
Copy the code

4.6 missingDimensionStrategy (dimension, requestedValue)

  • Similar method: missingDimensionStrategy(dimension, requestedValues) the difference is that the second parameter can set multiple flavors.
  • Dimension: (1) Dimension: (2) requestedValue: Flavor list (if requestedValues)
  • Description: Ignore the channel Settings in the Library, i.e. dimensions and flavors, otherwise they will not be introduced.
  • Usage:

Our project structure is as followszinclibrarybuild.gradleThe following channel configuration is prepared in

// Create flavor dimensions
flavorDimensions('zinc'.'handsome')
// Create product flavor
productFlavors {
    minApi13{
        dimension 'zinc'
    }
    minApi23{
        dimension 'zinc'
    }
    x86{
        dimension 'handsome'
    }
    arm64{
        dimension 'handsome'}}Copy the code

If you add a dependency directly to your app’s build.gradle, the synchronization will fail

dependencies{... Ignore other dependencies on implementationproject(":zinclibrary")}Copy the code

So we need to use this parameter in our app build.gradle to ignore the dimensions and flavors brought in by the library, using the following code

defaultConfig {
    missingDimensionStrategy 'zinc'.'minApi13'.'minApi23'
    missingDimensionStrategy 'handsome'.'x86'.'arm64'
}
Copy the code

4.7 resConfig (config)

  • Description: Reserved resource configuration.
  • Usage:
defaultConfig {
	// There are only two resources in apK: default and Chinese zh
	resConfig "zh"
}
Copy the code

4.8 resConfigs (config)

  • ResConfigs reserves multiple resources. ResConfigs reserves multiple resources.
  • Usage:
defaultConfig {
	// We compile apK with only "default", "Chinese en" and "English en" resources
	resConfigs "zh"."en"
}
Copy the code

4.9 resValue (type, name, value)

  • Description: Add a value resource
  • Usage:
defaultConfig {
	// Add to res/value, obtained by r.string.age
    resValue('string'.'age'.'12year')}Copy the code

4.10 targetSdkVersion (targetSdkVersion)

  • Description: Target version of the application. Note We have tested the specified version. You can use the API of this version during development. Otherwise, a message is displayed indicating that the API cannot be used. If this parameter is not set, the value is the same as minSdkVersion.
  • Usage:
defaultConfig {
	targetSdkVersion 28
}
Copy the code

Third, write at the end

Gradle configuration files look messy. In fact, we haven’t sorted them out completely. During this period of time, children will keep sorting them out and share them with others that are used in the project. If you like, please give me a like and follow me. If there is anything wrong in the article, please discuss it with me in the comments section and make progress together.

Project address: Please enter the portal