組件化gradle語法(一)

代碼地址:https://github.com/DaLeiGe/AndroidSamples/tree/master/NetEase_Modelar_Gradle
記錄一下Android組件化的學(xué)習(xí)過程郎哭,因?yàn)樽约洪_發(fā)過的項(xiàng)目基本都是一兩個(gè)人開發(fā),對組件化這一塊也沒去過多了解斑司,但是就大中型項(xiàng)目而言熟練掌握組件化開發(fā)是必不可少的技能匕坯,學(xué)習(xí)組件化之前先了解一下組件化需要用到的Gradle基本語法

1. Gradle打印hello world

在項(xiàng)目的build.gradle中使用println,如下兩種方式效果一樣

apply plugin: 'com.android.application'

println("hello wrold")
println "hell Gradle"

點(diǎn)擊build和左側(cè)的第二個(gè)按鈕查看執(zhí)行結(jié)果


image.png
2.創(chuàng)建自己的Gradle文件

一般創(chuàng)建一個(gè)Android項(xiàng)目AS會給我們創(chuàng)建好project和app的gradle碍庵,我們需要自己創(chuàng)建gradle存放app和個(gè)module的公共參數(shù)了赌,在項(xiàng)目根目錄右鍵-New-File創(chuàng)建一個(gè)config.gradle文件巩那,創(chuàng)建好項(xiàng)目目錄如下:


image.png

在config.gradle定義一個(gè)變量并在app.gradle引用
config.gradle

ext {
    username = "simon"
}

先在project.gradle中引用config.gradle吏夯,這樣就可以使用config.gradle配置的屬性了

//根目錄下的build.gradle頭部加入自定義的config.gradle,相當(dāng)于layout布局中加入include
apply from:"config.gradle"

app.gradle引用config.gradle定義的username有如下兩種方式

apply plugin: 'com.android.application'

println "$rootProject.ext.username"
println "${username}"

打印結(jié)果如下


image.png

Gradle同樣也支持其他數(shù)據(jù)類型,比如int即横、boolean噪生,map等,比如我們一般會在項(xiàng)目中把a(bǔ)pp和各module的defaultConfig參數(shù)和第三方implementation提取出來东囚,使用map鍵值對統(tǒng)一定義在config.gradle中

ext {
    username = "simon"

    //建立Map存儲跺嗽,對象名。key都可以自定義页藻,groovy糖果語法桨嫁,非常靈活
    androidId = [
            compileSdkVersion:28,
            applicationId   : "com.netease.modelar.gradle",
            minSdkVersion   : 21,
            targetSdkVersion: 28,
            versionCode     : 1,
            versionName     : "1.0",
    ]

    appId = [
            applicationId: "com.netease.modelar.gradle",
            library      : "com.netease.modular.library"
    ]

    supportLibrary = "28.0.0"http://${xxx}
    //第三方庫
    dependencies = [
            "appcompat"   : "com.android.support:appcompat-v7:${supportLibrary}",
            "recyclerview": "com.android.support:recyclerview-v7:${supportLibrary}",
            "constraint"  : "com.android.support.constraint:constraint-layout:1.1.3"
    ]
}

然后再app個(gè)gradle中調(diào)用config.gradle定義的這些參數(shù),保證了app和各module的版本和第三方庫版本一致
先把config.gradle中參數(shù)賦值

//復(fù)值與引用
def androidId = rootProject.ext.androidId
def appId = rootProject.ext.appId
def support = rootProject.ext.dependencies

再在需要的地方調(diào)用

apply plugin: 'com.android.application'

//println("hello wrold")
//println "hell Gradle"
println "$rootProject.ext.username"
println "${username}"

//復(fù)值與引用
def androidId = rootProject.ext.androidId
def appId = rootProject.ext.appId
def support = rootProject.ext.dependencies
def url = rootProject.ext.url

android {
    compileSdkVersion androidId.compileSdkVersion
    defaultConfig {
        applicationId appId.applicationId
        minSdkVersion androidId.minSdkVersion
        targetSdkVersion androidId.targetSdkVersion
        versionCode androidId.versionCode
        versionName androidId.versionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    buildTypes {
        debug {
            buildConfigField("String", "debug", "\"${url.debug}\"")
        }

        release {
            minifyEnabled false
            buildConfigField("String", "debug", "\"${url.release}\"")
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    //簡寫
    //implementation 'com.android.support:appcompat-v7:28.0.0'
    //使用自己配置config.gradle寫法
    implementation support.appcompat
    implementation support.recyclerview
    implementation support.constraint

}
3.dependencies->implementation的幾種寫法

在項(xiàng)目開發(fā)中我們會通過implementation使用到一些第三方庫份帐,一般會通過簡寫的方式進(jìn)行引用璃吧,比如

//簡寫
implementation 'com.android.support:appcompat-v7:28.0.0'

完整寫法:implementation group: 'xx', name: 'xx', version: 'xx'

implementation group: 'com.android.support', name: 'appcompat-v7', version: '28.0.0'

使用自己配置的config.gradle寫法

    implementation support.appcompat
    implementation support.recyclerview
    implementation support.constraint

最簡寫法,通過.each循環(huán)的方法添加引用,就可以全部implementation我們在config.gradle中定義的dependencies的map鍵值對

support.each { k, v -> implementation v }
4.使用Gradle配置正式/測試環(huán)境BaseUrl

在開發(fā)中我們一般都會通過一個(gè)工具類配置正式/測試環(huán)境的BaseUrl废境,然后每次打包的時(shí)候手動切換這個(gè)BaseUrl畜挨,通過Gradle可以動態(tài)配置BaseUrl避免疏忽造成忘記切換BaseUrl的尷尬。在config.gradle中添加isRelease和url=[]兩個(gè)屬性

ext {
    username = "simon"

    //建立Map存儲朦促,對象名。key都可以自定義栓始,groovy糖果語法务冕,非常靈活
    androidId = [
            compileSdkVersion:28,
            applicationId   : "com.netease.modelar.gradle",
            minSdkVersion   : 21,
            targetSdkVersion: 28,
            versionCode     : 1,
            versionName     : "1.0",
    ]

    appId = [
            applicationId: "com.netease.modelar.gradle",
            library      : "com.netease.modular.library"
    ]

    isRelease = true
    //生成/測試環(huán)境Url
    url = [
            "debug"  : "https://11.22.33.44/debug",
            "release": "https://11.22.33.44/release"
    ]

    supportLibrary = "28.0.0"http://${xxx}
    //第三方庫
    dependencies = [
            "appcompat"   : "com.android.support:appcompat-v7:${supportLibrary}",
            "recyclerview": "com.android.support:recyclerview-v7:${supportLibrary}",
            "constraint"  : "com.android.support.constraint:constraint-layout:1.1.3"
    ]
}

在app.gradle中buildTypes中配置

 buildTypes {
        debug {
            buildConfigField("String", "debug", "\"${url.debug}\"")
        }

        release {
            minifyEnabled false
            buildConfigField("String", "debug", "\"${url.release}\"")
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

重新Syno Now然后打開,打開如下目錄的BuildConfig.class這個(gè)類你會發(fā)現(xiàn)已近在改類中自動生成了一個(gè)url地址


image.png

debug包下為:

 public static final String debug = "https://11.22.33.44/debug";

release包下為:

 public static final String release = "https://11.22.33.44/release";
5.簽名配置

其中debug的簽名配置幻赚,windows系統(tǒng)默認(rèn)的Android debug簽名證書存儲路徑為:C://Users/Administrator/.android/debug.keystore禀忆,Mac系統(tǒng)的默認(rèn)簽名路徑為:~/.android/debug.keystore,一般為了避免同事之間電腦操作系統(tǒng)不同落恼,可以直接配置release簽名信息箩退,或者不配置debug,打包的時(shí)候會自動使用默認(rèn)的debug簽名證書進(jìn)行配置
注意:signingConfigs需要配置在buildTypes節(jié)點(diǎn)之前

    signingConfigs {
        debug {
            //windows系統(tǒng)默認(rèn)debug簽名證書存儲路徑
            //storeFile file("C://Users/Administrator/.android/debug.keystore")
            //Mac系統(tǒng)默認(rèn)debug簽名證書存儲路徑
            //storeFile file("~/.android/debug.keystore")
            //storePassword "android"
            //keyAlias "androiddebugkey"
            //keyPassword "android"
            storeFile file("../netease.jks")
            storeType "netease"
            storePassword "net163"
            keyAlias "netease"
            keyPassword "net163"
        }
        release {
            //簽名證書文件
            storeFile file("../netease.jks")
            //簽名證書的類型
            storeType "netease"
            //簽名證書文件的密碼
            storePassword "net163"
            //簽名證書中密碼別名
            keyAlias "netease"
            //簽名證書中該秘鑰的密碼
            keyPassword "net163"
            //是否開啟v2打包
            v2SigningEnabled true
        }
    }
6.項(xiàng)目中一些其他的Gradle配置

看注釋佳谦,都寫的很比較清楚戴涝,關(guān)于熱修復(fù)和分包的

apply plugin: 'com.android.application'

//println("hello wrold")
//println "hell Gradle"
println "$rootProject.ext.username"
println "${username}"

//復(fù)值與引用
def androidId = rootProject.ext.androidId
def appId = rootProject.ext.appId
def support = rootProject.ext.dependencies
def url = rootProject.ext.url

android {
    compileSdkVersion androidId.compileSdkVersion
    defaultConfig {
        applicationId appId.applicationId
        minSdkVersion androidId.minSdkVersion
        targetSdkVersion androidId.targetSdkVersion
        versionCode androidId.versionCode
        versionName androidId.versionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        //開啟分包
        multiDexEnabled true
        //設(shè)置分包配置
        //multiDexKeepFile file('multidex-config.txt')

        //將svg圖片生成 指定維度的png圖片
        //vectorDrawables.generatedDensities('xhdpi','xxhdpi')
        //使用support-v7兼容(5.0版本以上)
        vectorDrawables.useSupportLibrary = true
        //只保留指定和默認(rèn)資源
        resConfig('zh-rCH')

        //配置so庫CPU架構(gòu)(真機(jī):arm,模擬器:x86)
        // x86 x86_64 mips mips64
        ndk {
            //真機(jī)
            //abiFilters('armeabi', 'armeabi-v7')
            //為了模擬器啟動
            abiFilters('x86', 'x86_64')
        }

        //源集 - 設(shè)置源集的屬性,更改源集的Java目錄或者自由目錄等
        sourceSets {
            main {
                if (!isRelease) {
                    // 如果是組件化模式,需要單獨(dú)運(yùn)行時(shí)
                    manifest.srcFile 'src/main/AndroidManifest.xml'
                    java.srcDirs = ['src/main/java']
                    res.srcDirs = ['src/main/res']
                    resources.srcDirs = ['src/main/resources']
                    aidl.srcDirs = ['src/main/aidl']
                    assets.srcDirs = ['src/main/assets']
                } else {
                    //集成化模式啥刻,整個(gè)項(xiàng)目打包
                    manifest.srcFile 'src/main/AndroidManifest.xml'
                }
            }
        }
    }

    //簽名配置(隱形坑:必須寫在buildTypes之前)
    signingConfigs {
        debug {
            //windows系統(tǒng)默認(rèn)debug簽名證書存儲路徑
            //storeFile file("C://Users/Administrator/.android/debug.keystore")
            //Mac系統(tǒng)默認(rèn)debug簽名證書存儲路徑
            //storeFile file("~/.android/debug.keystore")
            //storePassword "android"
            //keyAlias "androiddebugkey"
            //keyPassword "android"
            storeFile file("../netease.jks")
            storeType "netease"
            storePassword "net163"
            keyAlias "netease"
            keyPassword "net163"
        }
        release {
            //簽名證書文件
            storeFile file("../netease.jks")
            //簽名證書的類型
            storeType "netease"
            //簽名證書文件的密碼
            storePassword "net163"
            //簽名證書中密碼別名
            keyAlias "netease"
            //簽名證書中該秘鑰的密碼
            keyPassword "net163"
            //是否開啟v2打包
            v2SigningEnabled true
        }
    }

    buildTypes {
        debug {
            buildConfigField("String",  "debug", "\"${url.debug}\"")
        }

        release {
            minifyEnabled false
            buildConfigField("String", "debug", "\"${url.release}\"")
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    //adbOptions:可以對adb操作選項(xiàng)添加配置
    adbOptions {
        //配置操作超時(shí)時(shí)間奸鸯,單位毫秒
        timeOutInMs = 5 * 1000_0
        //adb install 命令的選項(xiàng)配置
        installOptions '-r', '-s'
    }

    //對 dx 操作配置,接受一個(gè)DexOptions類型的閉包可帽,配置由DexOptions提供
    dexOptions {
        //配置執(zhí)行dx命令是為其分配的最大推內(nèi)存
        javaMaxHeapSize "4g"
        //配置是否執(zhí)行dex Library工程娄涩,開啟后會提高增量構(gòu)建速度,不會影響clean構(gòu)建速度映跟,默認(rèn)true
        preDexLibraries = false
        //配置是否開啟jumbo模式凭需,代碼方法超過65535需要強(qiáng)制開啟才能構(gòu)建成功
        jumboMode true
        //配置Gradle運(yùn)行dx命令時(shí)使用的線程數(shù)量
        threadCount 8
        additionalParameters = [
                '--multi-dex',//多dex分包
                '--set-max-idx-number=50000',//每個(gè)包內(nèi)方法數(shù)上限
                // '--main-dex-list=' + '/multidex-config.txt',// 打包到主classes.dex的文件列表
                '--minimal-main-dex'
        ]
    }

    //執(zhí)行 gradle lint 命令即可運(yùn)行 lint 檢查铺纽,默認(rèn)生成的報(bào)告在 outputs/lint-results.html中
    lintOptions {
        //遇到lint檢查錯(cuò)誤會終止構(gòu)建,一般設(shè)置為false
        abortOnError false
        //將警告當(dāng)做錯(cuò)誤來處理(老版本:warningAsErrors)
        warningsAsErrors false
        //檢查新的API
        check 'NewApi'
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    //標(biāo)準(zhǔn)寫法
    //implementation group: 'com.android.support', name: 'appcompat-v7', version: '28.0.0'
    //簡寫
    //implementation 'com.android.support:appcompat-v7:28.0.0'
    //使用自己配置config.gradle寫法
    //implementation support.appcompat
    //implementation support.recyclerview
    //implementation support.constraint
    //最簡潔的方式.each循環(huán)依賴
    support.each { k, v -> implementation v }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末咸包,一起剝皮案震驚了整個(gè)濱河市肿轨,隨后出現(xiàn)的幾起案子歼争,更是在濱河造成了極大的恐慌喻杈,老刑警劉巖勾栗,帶你破解...
    沈念sama閱讀 219,188評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異贷洲,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)晋柱,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評論 3 395
  • 文/潘曉璐 我一進(jìn)店門优构,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人雁竞,你說我怎么就攤上這事钦椭。” “怎么了碑诉?”我有些...
    開封第一講書人閱讀 165,562評論 0 356
  • 文/不壞的土叔 我叫張陵彪腔,是天一觀的道長。 經(jīng)常有香客問我进栽,道長德挣,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,893評論 1 295
  • 正文 為了忘掉前任快毛,我火速辦了婚禮格嗅,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘唠帝。我一直安慰自己屯掖,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,917評論 6 392
  • 文/花漫 我一把揭開白布襟衰。 她就那樣靜靜地躺著贴铜,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上绍坝,一...
    開封第一講書人閱讀 51,708評論 1 305
  • 那天徘意,我揣著相機(jī)與錄音,去河邊找鬼陷嘴。 笑死映砖,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的灾挨。 我是一名探鬼主播邑退,決...
    沈念sama閱讀 40,430評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼劳澄!你這毒婦竟也來了地技?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,342評論 0 276
  • 序言:老撾萬榮一對情侶失蹤秒拔,失蹤者是張志新(化名)和其女友劉穎莫矗,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體砂缩,經(jīng)...
    沈念sama閱讀 45,801評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡作谚,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,976評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了庵芭。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片妹懒。...
    茶點(diǎn)故事閱讀 40,115評論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖双吆,靈堂內(nèi)的尸體忽然破棺而出眨唬,到底是詐尸還是另有隱情,我是刑警寧澤好乐,帶...
    沈念sama閱讀 35,804評論 5 346
  • 正文 年R本政府宣布匾竿,位于F島的核電站,受9級特大地震影響蔚万,放射性物質(zhì)發(fā)生泄漏岭妖。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,458評論 3 331
  • 文/蒙蒙 一反璃、第九天 我趴在偏房一處隱蔽的房頂上張望区转。 院中可真熱鬧,春花似錦版扩、人聲如沸废离。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,008評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蜻韭。三九已至悼尾,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間肖方,已是汗流浹背闺魏。 一陣腳步聲響...
    開封第一講書人閱讀 33,135評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留俯画,地道東北人析桥。 一個(gè)月前我還...
    沈念sama閱讀 48,365評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像艰垂,于是被迫代替她去往敵國和親泡仗。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,055評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 版權(quán)聲明:本文為博主原創(chuàng)文章猜憎,未經(jīng)博主允許不得轉(zhuǎn)載娩怎。 https://blog.csdn.net/zhaoyanj...
    勤奮的pangdunhu閱讀 2,038評論 0 1
  • 1.介紹 如果你正在查閱build.gradle文件的所有可選項(xiàng),請點(diǎn)擊這里進(jìn)行查閱:DSL參考 1.1新構(gòu)建系統(tǒng)...
    Chuckiefan閱讀 12,138評論 8 72
  • 現(xiàn)在 android 開發(fā)中對于 gradle 也是很多技巧的胰柑,簡單的有統(tǒng)一管理依賴及其版本號截亦,復(fù)雜一些的涉及到 ...
    前行的烏龜閱讀 3,313評論 0 25
  • Gradle 是一款構(gòu)建系統(tǒng)工具,它的 DSL 基于 Groovy 實(shí)現(xiàn)柬讨。Gradle 構(gòu)建的大部分功能都是通過插...
    任教主來也閱讀 3,058評論 3 6
  • 不怕跌倒崩瓤,所以飛翔 組件化開發(fā) 參考資源 Android組件化方案 為什么要組件化開發(fā) 解決問題 實(shí)際業(yè)務(wù)變化非常...
    筆墨Android閱讀 2,984評論 0 0