Detailed explanation of Gradle configuration file of AndroidStudio

AndroidStudio之Gradle

This article mainly discusses the use of Gradle in AndroidStudio, and also explains the use of each configuration file in detail. If you do not know the basics of Gradle, you can read the basics of Gradle first, which will help you to discuss this topic today. Understand, understand the principle and use Gradle to do whatever you want;

Gradle in AndroidStudio

Gradle in AndroidStudio mainly uses 2 objects:

  • build.gradle corresponds to the Project object

  • setting.gradle corresponds to the Setting object

The whole process of building an AS project is as follows:

1. At the beginning of the construction, a Setting object will be created first;

2. Configure the Setting object according to the content of setting.gradle;

3. Load the Project through this Setting object, and how many Moudles are included will create as many Projects;

4. Configure the Project object according to the content of build.gradle;

Gradle and the Android Gradle Plugin

Gradle runs independently of AndroidStudio, and AndroidStudio only depends on Gradle's plug-ins. The two should not be confused.
- AndroidStudio configure Gradle

image
1. If you select "use defalut gradle wrapper(recommended)", AS will search for gradle according to the gradle-wrapper.properties file configuration in the project. The gradle-wrapper.properties configuration is as follows:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

When the project starts to compile, it will first look for the corresponding gradle under wrapper/dists from the gradle version directory configured in the environment variable. If it is not found, it will be downloaded according to the url corresponding to distributionUrl.
image

2. Of course, you can also choose "use local gradle distribution" and load the local gradle path.
If you choose local gradle, the local gradle will be used directly when compiling.

  • android gradle plugin

In build.gradle in the root directory, configure the gradle plugin version:

buildscript {

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}
  • Gradle and Android Gradle plugin
    version correspondence :

image

AndroidStudio Gradle file configuration interpretation

First, let's take a look at the AndroidStudio project structure

image

As can be seen from the above figure, a complete AndroidStudio project contains one or more Moudle and gradle configuration files

Detailed explanation of root build.gradle

/**
 * buildscript里是gradle脚本执行所需依赖,分别是对应的maven库和插件
 */
buildscript { 
    /**
    * 定义公共仓库
    */
    repositories {
        /**
         * 公共仓库名称
         */
        jcenter() //仓库名
        mavenCentral() //仓库名
    }
    /**
    * 定义依赖库
    */
    dependencies {
        /**
        * Android Gradle 插件版本
        */
        classpath 'com.android.tools.build:gradle:3.0.1'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

/**
 * 项目本身需要的依赖、配置所有Moudle共用的依赖;
 */
allprojects {
    repositories {
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}

/**
 * 系统自动生成的task
 */
task clean(type: Delete) {
    delete rootProject.buildDir
}

1. buildscript: Here are the dependencies required for gradle script execution, which are the corresponding maven libraries and plugins;

2. repositories{}: define public repositories;

3. jcenter(), mavenCentral(): public warehouse name;

4. allprojects: The dependencies required by the project itself, and the dependencies shared by all Moudles are configured;

5. task clean: task automatically generated by the system;

Moudle build.gradle详解

/**
 * 配置当前Module构建属性
 */
apply plugin: 'com.android.application'
//apply plugin: 'com.android.library'

/**
 * android{} 当前Moudle下项目构建配置选项
 */
android {
    compileSdkVersion 26
    buildToolsVersion 26.0.1

    /**
     * 配置项目编译版本号等属性,会覆盖AndroidManifest.xml中的配置
     */
    defaultConfig {
        applicationId "com.ailin.mvp"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1000
        versionName "1.0"
        /**
        * 设置支持的SO库架构
        */
        ndk {
            abiFilters 'armeabi', 'x86', 'armeabi-v7a'
        }
    }

    /**
     * 配置release版本所需要的签名文件等
     */
    signingConfigs {
        //配置变会员release版本
        release {
            storeFile file("./mvpapp.jks")
            storePassword "abc123"
            keyAlias "mvpapp"
            keyPassword "abc123"
        }
    }

    /**
    * 这里配置签名版本和调试版本,还可以自定义需要的版本
    */
    buildTypes {
        release {

            /**
             * 打开代码混淆功能
             */
            minifyEnabled true

            /**
             * 指定signingConfigs中定义的签名配置
             */
            signingConfig signingConfigs.release

            /**
             * 指定混淆代码的混淆文件,混淆文件由两部分组成:
             * proguard-android.txt:系统默认的android程序的混淆文件,这个文件的目录在 <sdk目录>/tools/proguard/proguard-android.txt
             * proguard-rules.pro:项目中自定义混淆文件
             */
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            debuggable true
            minifyEnabled false
            signingConfig signingConfigs.debug
        }
    }

}

/**
 * 指定依赖仓库
 */
repositories {
    /**
     * 指定远程仓库
     */
    maven { url 'https://jitpack.io' }

    /**
     * 指定当前Moudle根目录下文件名为libs的文件夹为本地仓库
     */
    flatDir { dirs 'libs' }
}

dependencies {

    /**
     * 指定当前Moudle根目录下文件名为libs的文件夹为本地仓库,并且引入所有.jar结尾的依赖文件
     */
    compile fileTree(include: ['*.jar'], dir: 'libs')

    /**
     * 依赖测试编译
     */
    testCompile 'junit:junit:4.12'

    /*
     * 编译时指定编译release版本还是debug版本
     */
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.4-beta2'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'

    /**
    * 只在编译的时候执行依赖的库,但是库最终不打包到apk中
    */
    annotationProcessor 'com.jakewharton:butterknife:8.2.1'

    /**
     * 在编译、运行时候需要依赖代码
     */
    compile 'com.alibaba:fastjson:1.2.23'

    /**
     * 编译的时候才用得上,而运行时不需要,不会写入apk
     */
    provided("com.tencent.tinker:tinker-android-anno:${TINKER_VERSION}") {
        changing = true 
    }

    /**
     * 引入libary Moudle
     */
    compile project(':RecyclerViewHelper')
    compile project(':downloaderLib')
    compile project(':playerview')
    compile project(':tinkerLib')
}

/**
 * 引入自定义扩展配置文件
 */
apply from: 'tinker_build.gradle'

It is also possible to configure the variables used by the generated java files

android {
    defaultConfig {
        ......
        buildConfigField "int", "count", "0"
    }

    buildTypes {
        debug{
            buildConfigField "boolean", "isDebug", "true"
        }
    }
}

After adding the above code, it will be generated in the BuildConfig file in the build directory after compilation, and then it can be used in the project
image
image

Detailed explanation of gradle-wrapper.properties

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

This configuration file has been analyzed above and will not be repeated here;

Detailed explanation of proguard-rules.pro

#指定代码的压缩级别
-optimizationpasses 5

#包名不混合大小写
-dontusemixedcaseclassnames

#不忽略非公共的库类
-dontskipnonpubliclibraryclasses

#优化/不优化输入的类文件
-dontoptimize

#预校验
-dontpreverify

#混淆时是否记录日志
-verbose

#混淆时所采用的算法
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*

#忽略警告
-ignorewarning

#保护注解
-keepattributes *Annotation*

#保护反射的正常调用
-keepattributes Signature
-keepattributes EnclosingMethod

#不混淆哪些类
-keep public class * extends android.app.Fragment
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class com.android.vending.licensing.ILicensingService


#不混淆所有View的子类及其子类的get、set方法
-keep public class * extends android.view.View {
        public <init>(android.content.Context);
        public <init>(android.content.Context, android.util.AttributeSet);
        public <init>(android.content.Context, android.util.AttributeSet, int);
        public void set*(...);
        public *** get*();
}

#指定不混淆所有的JNI方法
-keepclasseswithmembernames class * {
    native <methods>;
}

#不混淆Activity中参数类型为View的所有方法
-keepclassmembers class * extends android.app.Activity {
       public void *(android.view.View);
}

#不混淆Parcelable和它的子类,还有Creator成员变量
-keep class * implements android.os.Parcelable {
      public static final android.os.Parcelable$Creator *;
}

#不混淆Serializable接口
-keepnames class * implements java.io.Serializable

#不混淆Serializable接口的子类中指定的某些成员变量和方法
-keepclassmembers class * implements java.io.Serializable {
        static final long serialVersionUID;
        private static final java.io.ObjectStreamField[] serialPersistentFields;
        !static !transient <fields>;
        !private <fields>;
        !private <methods>;
        private void writeObject(java.io.ObjectOutputStream);
        private void readObject(java.io.ObjectInputStream);
        java.lang.Object writeReplace();
        java.lang.Object readResolve();
}

#不混淆R类里及其所有内部static类中的所有static变量字段
-keepclassmembers class **.R$* {
        public static <fields>;
}

#如果有用到Gson解析包的,直接添加下面这几行就能成功混淆,不然会报错。
-keep class sun.misc.Unsafe { *; }
-keep class com.google.gson.examples.android.model.** { *; }

#如果有用到WebView的JS调用接口,需加入如下规则。
-keepclassmembers class fqcn.of.javascript.interface.for.webview {
       public *;
}

#apk包内所有class的内部结构
-dump class_files.txt
#未混淆的类和成员
-printseeds seeds.txt
#列出从apk中删除的代码
-printusage unused.txt
#混淆前后的映射
-printmapping mapping.txt

#忽略某个类的警告
-dontwarn com.unionpay.**
#不混淆某个类和成员变量
-keep class com.unionpay.** { *; }

-dontwarn android.support.**
-dontwarn com.flurry.**
-dontwarn com.paypal.**
-dontwarn org.lucasr.**
-dontwarn org.android.agoo.ut.impl.**

Detailed explanation of gradle.properties

  • gradle.properties is used to configure global variables, such as defining some commonly used variables:
/**
 * 指定JVM内存大小
 */
org.gradle.jvmargs=-Xmx1536m 

/**
 * 应用版本名称
 */
PACKAGE_ID=com.ailian.gradlestudy

/**
 * 应用版本名称
 */
VERSION_NAME=1.0.0

/**
 * 应用版本号
 */
VERSION_CODE=100

/**
 * 支持库版本
 */
SUPPORT_LIBRARY=26.2.1

/**
 * 最新支持SDK版本号
 */
ANDROID_BUILD_MIN_SDK_VERSION=19

/**
 * TARGET_SDK_VERSION
 */
ANDROID_BUILD_TARGET_SDK_VERSION=24

/**
 * BUILD_SDK_VERSION
 */
ANDROID_BUILD_SDK_VERSION=26

/**
 * BUILD_TOOLS_VERSION
 */
ANDROID_BUILD_TOOLS_VERSION=26.0.3
  • Use in other configuration files
android {
    compileSdkVersion project.ANDROID_BUILD_SDK_VERSION as int
    defaultConfig {
        applicationId project.APPLICATION_ID
        minSdkVersion project.ANDROID_BUILD_MIN_SDK_VERSION as int
        targetSdkVersion project.ANDROID_BUILD_TARGET_SDK_VERSION as int
        versionCode = project.VERSION_CODE as int
        versionName project.VERSION_NAME
    }
}

Details of settings.gradle

include ':app', ':RecyclerViewHelper', ':downloaderLib', ':playerview', ':tinkerLib'

settings.gradle is mainly used for Moudle to load configuration:

1. There needs to be a ':app' here. This Moudle is generated by default when the project is created. If there is only one ':app' Moudle in the project, settings.gradle does not need to be configured, because gradle will load the file named app by default. Moudle;

2. The name of the ':app' module can be modified. If the module name is changed, it must be declared in settings.gradle;

3. The ':app' module is the main module of the project. The main difference between app Moudle and other Moudles is:

app:
apply plugin: 'com.android.application'

其他Moudle:
apply plugin: 'com.android.library'

Detailed explanation of local.properties

/**
 * 配置项目支持NDK
 */
ndk.dir=/Users/ailian/sdk/ndk-bundle

/**
 * 配置项目支持SDK
 */
sdk.dir=/Users/ailian/sdk

local.properties can also add other properties

keyfile=./groovy.jks
keyAlias=groovy
keyPassword=adb123
storePassword=adb123

配置文件中使用方式

signingConfigs {
        release {
            def sdkDir = properties.getProperty('keyfile')
            storeFile file(sdkDir)
            def keyAliass = properties.getProperty('keyAlias')
            keyAlias keyAliass
            def keyPasswords = properties.getProperty('keyPassword')
            keyPassword keyPasswords
            def storePasswords = properties.getProperty('storePassword')
            storePassword storePasswords
        }
    }

Well, the configuration of gradle in AndroidStudio is finished here. Of course, there are many configurations of gradle. Interested students can study it by themselves. If there is anything wrong with the above explanation, please correct me;

Summarize

It is still mentioned in the opening chapter. If you want to use gradle to build powerful projects for us, you must understand its principles and usage.

The Basics of Gradle

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325575607&siteId=291194637