天天看点

Android Gradle详解

1. 单个项目设置代理

在项目的根目录下的gradle.properties文件中添加

systemProp.http.proxyHost=127.0.0.1
# 代理软件端口
systemProp.http.proxyPort=1080
systemProp.https.proxyHost=127.0.0.1
# 代理软件端口
systemProp.https.proxyPort=1080
           

2. 全局代理设置

C:\Users\Administrator\

(其中Administrator是用户名)下, 新建gradle.properties文件,往里面添加如下内容.

systemProp.http.proxyHost=127.0.0.1
# 代理软件端口
systemProp.http.proxyPort=1080
systemProp.https.proxyHost=127.0.0.1
# 代理软件端口
systemProp.https.proxyPort=1080
           

3. 签名文件配置

1). 在主module根目录下的新建signing.properties文件

KEYSTORE_FILE=你的keystore文件位置
KEYSTORE_PASSWORD= 你的keystore文件密码
KEY_ALIAS= 你的keystore文件用到的别名
KEY_PASSWORD= 你的keystore文件用到的别名的密码
           

2). build.gradle加载

//加载签名配置的文件
Properties props = new Properties()props.load(new
FileInputStream(file("signing.properties")))
android {
  signingConfigs {    
    release{        
        //设置release的签名信息       
        keyAlias props['KEY_ALIAS']        
        keyPassword props['KEY_PASSWORD']        
        storeFile file(props['KEYSTORE_FILE'])        
        storePassword props['KEYSTORE_PASSWORD']    
    }
  }

...

  buildTypes {
      debug {
        ...
        signingConfig signingConfigs.release
      }
      ...    
      release {
        ...
        signingConfig signingConfigs.release
    }
  }
}
           

4. 多渠道打包

1). 配置AndroidManifest.xml

<meta-data android:name="UMENG_CHANNEL" android:value="${UMENG_CHANNEL_VALUE}" />
           

2). build.gradle文件中的设置

productFlavors { 
  wandoujia  { 
    manifestPlaceholders = [UMENG_CHANNEL_VALUE: "wandoujia"] 
  } 
  xiaomi  { 
    manifestPlaceholders = [UMENG_CHANNEL_VALUE: "xiaomi"] 
  }
  qq  { 
    manifestPlaceholders = [UMENG_CHANNEL_VALUE: "qq"] 
  } 
  360  { 
    manifestPlaceholders = [UMENG_CHANNEL_VALUE: "360"] 
  }
}
           

简便写法:

android {
  ...

  buildTypes {
      debug {
        ...
      }
      ...    
      release {
        ...
        productFlavors { 
            wandoujia{} 
            xiaomi{} 
            qq{} 
            360 {} 
        } 
        productFlavors.all { flavor -> flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name] 
      }
    }
}
           

3). 一次生成所有渠道包

gradle assembleRelease
           

4). 修改导出包的文件目录和apk名称

ext {
    out_put_file = "G:\\test"
}
// 定义一个打包时间
def releaseTime() {    
      return new Date().format("yyyyMMdd", TimeZone.getTimeZone("UTC"))
}

android {
  ...

  buildTypes {
      debug {
        ...
      }
      ...    
      release {
        ...
        applicationVariants.all {
                variant -> variant.outputs.each { output ->
                    def outputFile = output.outputFile

                    if (null != outputFile && outputFile.name.endsWith('.apk')) {
                        // 输出apk名称为debug_v1.0.0_2018_03_21.apk
                        def isDebug = outputFile.name.split('.apk')[0].toString().split('-')[1]
                        def fileName = "${isDebug}_v${defaultConfig.versionName}_${releaseTime()}.apk"
                        // 控制输出APK的存放路径
                        if (!"".equals(out_put_file)) {
                            File output_dir = file(out_put_file)
                            output.outputFile = new File(output_dir, fileName)
                            println "输出文件位置:" + output.outputFile
                        } else {
                            output.outputFile = new File(outputFile.parent, fileName)
                            println "输出文件位置:" + output.outputFile
                        }
                    }
                }
            }
      }
  }
}
           

5. 多工程全局配置

1). 在project的根目录下的build.gradle定义ext全局变量

ext { 
  compileSdkVersion = 22 
  buildToolsVersion = "23.0.1" 
  minSdkVersion = 10 
  targetSdkVersion = 22 
  versionCode = 34 
  versionName = "v2.6.1"
}
           

2). 在各module的build.gradle中引用

android { 
  compileSdkVersion rootProject.ext.compileSdkVersion 
  buildToolsVersion rootProject.ext.buildToolsVersion 

  defaultConfig { 
    applicationId "com.xxx.xxx" 
    minSdkVersion rootProject.ext.minSdkVersion 
    targetSdkVersion rootProject.ext.targetSdkVersion 
    versionCode rootProject.ext.versionCode 
    versionName rootProject.ext.versionName 
  }
}
           

6. 混淆代码

//混淆编译
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
           

7. 当前的编译时间、编译的机器、最新的commit版本添加到apk

android { 
  defaultConfig { 
      resValue "string", "build_time", buildTime() 
      resValue "string", "build_host", hostName() 
      resValue "string", "build_revision", revision() 
  }
}

def buildTime() { 
      return new Date().format("yyyy-MM-dd HH:mm:ss")
}

def hostName() { 
      return System.getProperty("user.name") + "@" + InetAddress.localHost.hostName
}

def revision() { 
      def code = new ByteArrayOutputStream() 
      exec { 
        commandLine 'git', 'rev-parse', '--short', 'HEAD' 
        standardOutput = code 
      } 
      return code.toString()
}
           

8. buildConfigField自定义配置

buildTypes { 
  debug { 
    buildConfigField "boolean", "LOG_DEBUG", "true"//是否输出LOG信息   
    buildConfigField "String", "API_HOST", "\"http://api.test.com\""//API Host 
  } 
}
           

9. dex突破65535的限制

1). 在defaultConfig节点使能多DEX功能

2). 引入multidex库文件

dependencies { 
  compile 'com.android.support:multidex:1.0.0' 
}
           

3). 继承MultiDexApplication

10. Task任务

1). 获取全部任务

gradlew tasks -q
           

其中-q表示忽略gradle本身的log信息,加上这个参数可以屏蔽很多无关的输出,不加也不会影响执行。执行后显示如下:

F:\test\GradleTest>gradlew tasks -q


------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Android tasks
-------------
androidDependencies - Displays the Android dependencies of the project.
signingReport - Displays the signing info for each variant.
sourceSets - Prints out all the source sets defined in this project.

Build tasks
-----------
assemble - Assembles all variants of all applications and secondary packages.
assembleAndroidTest - Assembles all the Test applications.
assembleDebug - Assembles all Debug builds.
assembleRelease - Assembles all Release builds.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
clean - Deletes the build directory.
compileDebugAndroidTestSources
compileDebugSources
compileDebugUnitTestSources
compileReleaseSources
compileReleaseUnitTestSources
mockableAndroidJar - Creates a version of android.jar that's suitable for unit tests.

Build Setup tasks
-----------------
init - Initializes a new Gradle build. [incubating]
wrapper - Generates Gradle wrapper files. [incubating]

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'GradleTest'.
components - Displays the components produced by root project 'GradleTest'. [incubating]
dependencies - Displays all dependencies declared in root project 'GradleTest'.
dependencyInsight - Displays the insight into a specific dependency in root project 'GradleTest'.
help - Displays a help message.
model - Displays the configuration model of root project 'GradleTest'. [incubating]
projects - Displays the sub-projects of root project 'GradleTest'.
properties - Displays the properties of root project 'GradleTest'.
tasks - Displays the tasks runnable from root project 'GradleTest' (some of the displayed tasks may belong to subprojects).

Install tasks
-------------
installDebug - Installs the Debug build.
installDebugAndroidTest - Installs the android (on device) tests for the Debug build.
uninstallAll - Uninstall all applications.
uninstallDebug - Uninstalls the Debug build.
uninstallDebugAndroidTest - Uninstalls the android (on device) tests for the Debug build.
uninstallRelease - Uninstalls the Release build.

Verification tasks
------------------
check - Runs all checks.
connectedAndroidTest - Installs and runs instrumentation tests for all flavors on connected devices.
connectedCheck - Runs all device checks on currently connected devices.
connectedDebugAndroidTest - Installs and runs the tests for debug on connected devices.
deviceAndroidTest - Installs and runs instrumentation tests using all Device Providers.
deviceCheck - Runs all device checks using Device Providers and Test Servers.
lint - Runs lint on all variants.
lintDebug - Runs lint on the Debug build.
lintRelease - Runs lint on the Release build.
test - Run unit tests for all variants.
testDebugUnitTest - Run unit tests for the debug build.
testReleaseUnitTest - Run unit tests for the release build.

Other tasks
-----------
clean
extractProguardFiles
jarDebugClasses
jarReleaseClasses
transformResourcesWithMergeJavaResForDebugUnitTest
transformResourcesWithMergeJavaResForReleaseUnitTest

To see all tasks and more detail, run gradlew tasks --all
           

2). 创建任务

// 定义任务
task hello
// 附带的动作--最后一个
hello.doLast {
    println("hello doLast")
}
// 附带的动作--第一个
hello.doFirst {
    println("hello doFirst")
}
           

添加的位置在Other tasks任务中会出现

Android Gradle详解

task.png

3). 执行任务

gradlew hello -q
           

结果:

Android Gradle详解

hello task.png

4). 依赖

// 定义任务
task hello
// 附带的动作--最后一个
hello.doLast {
    println("hello doLast")
}
// 附带的动作--第一个
hello.doFirst {
    println("hello doFirst")
}
// 依赖
task world(dependsOn: "hello") << {
    println("world")
}
           

执行结果:

Android Gradle详解

world task.png

其中:

task xxx << {
}
这样的语法等价于
task xxx
xxx.dolast {
}
           

11. 查看包依赖关系

gradlew.bat :app:dependencies --configuration compile