天天看點

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