android studio 3.0 升级问题:原来module中的包没法引用

问题

Android studio升级到3.0以上之后,也随之升级到了3.0.0版本。

classpath 'com.android.tools.build:gradle:3.0.0'
  • 1

在3.0版本中,compile 指令被标注为过时方法,而新增了两个依赖指令,一个是implement 和api,这两个都可以进行依赖添加,但是有什么区别呢?

implementation和api的区别。

新建工程默认生成的app的build.gradle文件中的依赖:

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

api 指令

完全等同于compile指令,没区别,你将所有的compile改成api,完全没有错。

implementation指令

这个指令的特点就是,对于使用了该命令编译的依赖,对该项目有依赖的项目将无法访问到使用该命令编译的依赖中的任何程序,也就是将该依赖隐藏在内部,而不对外部公开。

简单的说,就是使用implementation指令的依赖不会传递。 
例如,有一个module为testsdk,testsdk依赖于gson:

implementation 'com.google.code.gson:gson:2.8.2'
  • 1
  • 2

这时候,在testsdk里边的java代码是可以访问gson的。

另一个module为app,app依赖于testsdk:

implementation project(':testsdk')
  • 1
  • 2

这时候,因为testsdk使用的是implementation 指令来依赖gson,所以app里边不能引用gson。

但是,如果testsdk使用的是api来引用gson:

api 'com.google.code.gson:gson:2.8.2'
  • 1
  • 2

则与gradle3.0.0之前的compile指令的效果完全一样,app的module也可以引用gson。这就是api和implementation的区别。

建议

在Google IO 相关话题的中提到了一个建议,就是依赖首先应该设置为implementation的,如果没有错,那就用implementation,如果有错,那么使用api指令。使用implementation会使编译速度有所增快。

参考:

http://blog.csdn.net/soslinken/article/details/73114637

https://zhuanlan.zhihu.com/p/27475883

https://stackoverflow.com/questions/44413952/gradle-implementation-vs-api-configuration

http://blog.csdn.net/JF_1994/article/details/52781751

猜你喜欢

转载自blog.csdn.net/qq_26075861/article/details/80570699