gradle配置優化及dependencies中各種依賴方式說明


一.前言
當我們用AndroidStudio新建項目時候發現默認的compile已經改為了implementation.
implementation以前並沒有接觸過,這里干脆總結一下dependencies中各種依賴方式的區別.

二.各種依賴方式說明
implementation
這個指令的特點就是,對於使用了該命令編譯的依賴,對該項目有依賴的項目將無法訪問到使用該命令編譯的依賴中的任何程序,也就是將該依賴隱藏在內部,而不對外部公開。
api
完全等同於compile指令。

compile
這種是我們最常用的方式,使用該方式依賴的庫將會參與編譯和打包。

testCompile
testCompile 只在單元測試代碼的編譯以及最終打包測試apk時有效。
debugCompile
debugCompile 只在debug模式的編譯和最終的debug apk打包時有效。
releaseCompile
releaseCompile 僅僅針對Release模式的編譯和最終的Release apk打包。這里比如
這里比如我們使用的leakcanary

debugCompile 'com.squareup.leakcanary:leakcanary-android:1.+'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.+'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.+'
 
provided
只在編譯時有效,不會參與打包,可以在自己的moudle中使用該方式依賴。比如com.android.support,gson這些使用者常用的庫,避免沖突。

apk(runtimeOnly)
只在生成apk的時候參與打包,編譯時不會參與,很少用。

三.依賴版本號處理
正常我們引入一個庫可能直接指定了版本號
compile ‘com.google.code.gson:gson:2.8.0’
那么可以不指定版本號嗎?答案是可以的,比如:
compile ‘com.google.code.gson:gson:2.+’ 引入gson 大版本為2的包
compile ‘com.google.code.gson:gson:latest.release’引入gson 最新的包

四.統一管理版本號
1.在根目錄下的build.gradle文件下添加 ext{ …. } 中的內容

ext{
//dependencies
supportLibraryVersion ='26.1.0'
gsonVersion = '2.8.0'
}
 
使用示例
compileSdkVersion rootProject.ext.COMPILE_SDK_VERSION

2.使用自定義gradle
當然以上方式還有更好的解決方案
首先我們在項目根目錄下創建一個任意命名的xxx.gradle文件. 例如 : config.gradle

ext {
android = [
compileSdkVersion: 26,
buildToolsVersion: "25.0.0",
minSdkVersion : 14,
targetSdkVersion : 22,
versionCode : 17,
versionName : "1.7",
applicationId : "com.king.headline",
applicationId2222: "com.king.headline",
]

dependencies = [
appcompatv7: "com.android.support:design:22.2.0",
loadtoast: "net.steamcrafted:load-toast:1.0.6",
constraintlayout: "com.android.support.constraint:constraint-layout:1.0.2"
]

}
 
使用

根目錄下的build.gradle於引用當前gradle
apply from : “config.gradle”
app下的build.gradle先定義出引用
def cfg = rootProject.ext.android
def dpc = rootProject.ext.dependencies
使用
compileSdkVersion cfg.compileSdkVersion
buildToolsVersion cfg.buildToolsVersion
4.完整示例
apply plugin: 'com.android.application'
def cfg = rootProject.ext.android
def dpc = rootProject.ext.dependencies
android {
compileSdkVersion cfg.compileSdkVersion
buildToolsVersion cfg.buildToolsVersion

defaultConfig {
applicationId "com.king.headline"
minSdkVersion 14
targetSdkVersion 22
versionCode 17
versionName "1.7"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile dpc.loadtoast
compile dpc.appcompatv7
compile dpc.constraintlayout
}
————————————————
版權聲明:本文為CSDN博主「金福林」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/jinfulin/article/details/80421927


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM