1. 程式人生 > >關於Android Studio裡的Gradle,你所需要知道的都在這裡了

關於Android Studio裡的Gradle,你所需要知道的都在這裡了

前言

你是不是有這種感覺,每當你使用Android Studio的時候,總會被她的優雅和便捷深深的吸引,但是一旦開啟build.gradle檔案就有一種想死的衝動,這尼瑪都是什麼啊,老子看不懂啦(ノಠ益ಠ)ノ彡┻━┻ ,不要著急,這篇文章就是來解救你的,看完這篇文章,你的種種疑問都會迎刃而解,從此與Android Studio過上快樂幸福的生活。(大霧→_→)

Gradle介紹

Gradle是一個先進的build toolkit,可以方便的管理依賴包和定義自己的build邏輯。到底有多先進,Android Studio官方整合Gradle,Google還專門寫了Android Plugin for Gradle,你們感受一下。

基礎配置

Android Studio中有一個頂級的build.gradle檔案,每一個module還有一個自己的build.gradle。這個檔案是使用Groovy語法和Android Plugin for Gradle元素的配置檔案。通常我們只需要修改module的build檔案就可以了。
下面是一個簡單的例子

apply plugin: 'com.android.application'

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"

    defaultConfig {
        applicationId "com.example.my.app"
        minSdkVersion 8
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {

     // Module dependency
    compile project(":lib")

    // Remote binary dependency
    compile 'com.android.support:appcompat-v7:19.0.1'

    // Local binary dependency
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

第一句apply plugin: ‘com.android.application’說明在這個build檔案中使用Android plugin for Gradle,有了這一句後,那些針對Android的元素才有意義。比如android {…}這個就是配置所有針對Android專案build時的選項。

  • compileSdkVersion: 編譯時用的sdk版本
  • buildToolsVersion: build工具的版本
  • defaultConfig: 動態的在build時配置AndroidManifest.xml裡的專案,defaultConfig裡的配置可以覆蓋manifest裡的配置。
  • buildTypes:
     配置如何構建和打包你的App,預設有debug和release兩個型別。debug型別包含除錯時的資訊,並且有debug key簽名。release預設是不含簽名的。本例中release版本用了ProGuard。
  • dependencies: 在android {…}這個元素之外,配置此模組的依賴。

依賴

dependencies {

     // Module dependency
    compile project(":lib")

    // Remote binary dependency
    compile 'com.android.support:appcompat-v7:19.0.1'

    // Local binary dependency
    compile fileTree(dir: 'libs', include: ['*.jar'])
}
  • 模組依賴: compile project(“:lib”),表明本模組依賴於lib模組,編譯的時候系統會把lib模組包含進來
  • 遠端的二進位制依賴: compile ‘com.android.support:appcompat-v7:19.0.1’,當本地沒有此依賴時會預設從Maven Central Repository下載相應的依賴。從哪裡下載可以在頂級的build檔案中配置。
  • *本地二進位制依賴:**compile fileTree(dir: ‘libs’, include: [‘.jar’]),把jar包拷貝到/libs資料夾下,compile fileTree(dir: ‘libs’, include: [‘*.jar’])意思是,app/libs下的所有jar包都包含進來

ProGuard

ProGuard的作用是在byte級別對你的app進行分析優化,使得你的App變得更小,更快。值得一提的是,當你使用某些開源專案時,他們會提醒你把一些包排除在ProGuard裡,防止出錯。

android {
    ...
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

getDefaultProguardFile(‘proguard-android.txt’)獲得預設的ProGuard配置。每個模組也都有模組級別的ProGuard規則,在proguard-rules.pro這個檔案裡,當然你也可以自己配置ProGuard規則。關於ProGuard的詳細配置,請參考ProGuard Manual

Application ID

Application ID是用來唯一標識要發行的應用的。在build.gradle裡設定。

   defaultConfig {
        applicationId "com.example.my.app"
        minSdkVersion 15
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }

系統允許你對不同的產品型別設定不同的id,比如免費版和高階版。

productFlavors {
        pro {
            applicationId = "com.example.my.pkg.pro"
        }
        free {
            applicationId = "com.example.my.pkg.free"
        }
    }

    buildTypes {
        debug {
            applicationIdSuffix ".debug"
        }
    }

配置簽名

debug版本與release版本的區別在於是否可以在一個安全的裝置上debug和APK如何被簽名的。在debug版本中,系統會提供一個預設的key來簽名和已知的證書來授權App,避免在構建的時候出現密碼提示。但是在release版本中,除非你主動提供一個key,不然系統是不會構建此專案的。

Release簽名步驟

  1. 建立keystore。keystore是一個包含一系列私鑰的二進位制檔案,這個檔案必須妥善保管。
  2. 建立一個私鑰。一個私鑰代表著一個app實體。
  3. 在build檔案中配置
android {
    ...
    defaultConfig { ... }
    signingConfigs {
        release {
            storeFile file("myreleasekey.keystore")
            storePassword "password"
            keyAlias "MyReleaseKey"
            keyPassword "password"
        }
    }
    buildTypes {
        release {
            ...
            signingConfig signingConfigs.release
        }
    }
}

4.在Android Studio中啟動assembleRelease。app/build/apk/app-release.apk這個檔案就是包含你release key的apk了。
注:一般不會直接在build檔案中寫入密碼的,密碼資訊可以寫在環境變數中

storePassword System.getenv("KSTOREPWD")
keyPassword System.getenv("KEYPWD")

或者用命令列輸入

storePassword System.console().readLine("\nKeystore password: ")
keyPassword System.console().readLine("\nKey password: ")

在Android Studio中配置簽名

  1. 選單欄裡,點選Build > Generate Signed APK.
  2. 在彈出的窗口裡點選Create new
  3. 填寫相關資訊
    key
  4. Build Type 選擇release
    type

到此為止,你就可以去應用市場釋出你的應用啦 ^_^

Build變數

定義productFlavors

有時你需要對同一個App發行不同的版本,如免費版、付費版之類的。這時你就需要用到productFlavors了。

android {
    ...
    defaultConfig { ... }
    signingConfigs { ... }
    buildTypes { ... }
    productFlavors {
        demo {
            applicationId "com.buildsystemexample.app.demo"
            versionName "1.0-demo"
        }
        full {
            applicationId "com.buildsystemexample.app.full"
            versionName "1.0-full"
        }
    }
}

productFlavors裡的配置會覆蓋defaultConfig裡的配置,如上配置後,系統會為每一個不同版本使用一個不同的id。

給每一個版本新增對應的資源

當你有不同的版本的時候,不同版本之間肯定有不同,所以需要新增不同的資源。以demo版為例,在src目錄下新建以下目錄

demo

把需要的Activity,String.xml等資源加入到對應資料夾下。
在IDE左側的Build Variants窗口裡就可以看到如下四個Build變數

tupian

這樣你需要哪個版本,直接選擇就可以了。

最後

看到這裡,再次開啟build.gradle這個檔案也不是感覺也沒那麼複雜了?是不是更愛Android Studio了?如有什麼問題歡迎留言討論。喜歡的話別忘了點個“頂”啊 ♪(^∀^●)ノ