Gradle依赖引入介绍

1. 引入关键字列表

4.x+版本 老版本(弃用) 说明
api compile 打包并传递
implementation compile 打包不传递
compileOnly provided 只在编译时用
runtimeOnly apk 只在运行时用 打包到apk
testImplementation testCompile 只在test用 打包到测试包
androidTestImplementation androidTestCompile 只在android test用 打包到测试包
debugImplementation debugCompile 只在debug模式有效 打包到debug包
releaseImplementation releaseCompile 只在release模式有效 打包到release包

2. 关键字说明

api

打包输出到aar或apk,并且依赖向上传递。

implementation

打包输出到aar或apk,依赖不传递。

compileOnly

编译时使用,不会打包到输出(aar或apk)。

runtimeOnly

只在生成apk的时候参与打包,编译时不会参与,很少用。

testImplementation

只在单元测试代码的编译以及最终打包测试apk时有效。

androidTestImplementation

只在Android相关单元测试代码的编译以及最终打包测试apk时有效。

debugImplementation

只在 debug 模式的编译和最终的 debug apk 打包时有效

releaseImplementation

仅仅针对 Release 模式的编译和最终的 Release apk 打包。

3. 各种依赖写法

本地项目依赖

dependencies {
    implementation project(':projectABC')
}

本地包依赖

dependencies {
    // 批量引入
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    // 单个引入
    implementation files('libs/aaa.jar', 'libs/bbb.jar')
    implementation files('x/y/z/ccc.jar')
}

远程包依赖

dependencies {
    // 简写
    implementation 'androidx.appcompat:appcompat:1.0.2'
    // 完整写法
    implementation  group: 'androidx.appcompat', name:'appcompat', version:'1.0.2'
}
根据Task类型(debug, release, test)引入
dependencies {
    // test
    testImplementation 'junit:junit:4.12'
    // android test  
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    // debug
    debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.0-beta-2'
    // release
    releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:2.0-beta-2'
}
排除引用(解决引入冲突)
dependencies {
    implementation ('com.github.bumptech.glide:glide:4.9.0'){
        exclude group:'com.android.support', module: 'support-fragment'
        exclude group:'com.android.support', module: 'support-core-ui'
        exclude group:'com.android.support', module: 'support-compat'
        exclude group:'com.android.support', module: 'support-annotations'
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章