一、几种依赖方式
- Compile 默认的依赖方式,任何情况下都会依赖。
- Provided 只提供编译时依赖,打包时不会添加进去。
- Apk 只在打包Apk包时依赖,这个应该是比较少用到的。
- TestCompile 只在测试时依赖,对应androidTestCompile
- DebugCompile 只在Debug构建时依赖
- ReleaseCompile 只在Release构建时依赖
注意:关于测试依赖,在项目中有androidTestCompile和testCompile,如:
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
testCompile 'junit:junit:4.12'
- androidTestCompile是用来测试api的,对应于目录是src/androidTest,运行在android设备或者虚拟机上.
- testCompile 是用来单元测试的,对应于目录的src/test,允许一般的java JVM,可以坐脱离设备的测试.
使用:
可以直接在Project Structure中设定更改
二、项目中可能的问题
1、普通依赖时差异化构建的错误
例如:
在项目中引用了debugCompile 'com.facebook.stetho:stetho:1.5.0'
然后进行了初始化:
这个时候直接运行是ok的,因为默认是debug模式,但是如果此时打release包的时候会出现如下错误:
这是因为,stetho的引用为debugCompile,也就是说,这个第三方只有在debug的时候才会依赖,release包的时候不会被依赖,但是在TestApplication中又执行了初始化代码,所以会出现找不到类的错误,下面给出一种解决办法:
也就是在src的目录下建立debug和release目录,并且两者的包结构要完全一致(其实main、test等包结构也要一致的)。这样的话看起来怪怪的,可以将debug和release不同的初始化放在各自下面,然后将TestApplication放在main下面并进行调用:
debug下的SdkManager代码:
public class SdkManager {
public static void init(Context context) {
Stetho.initializeWithDefaults(context);
}
}
release下的SdkManager代码:
public class SdkManager {
public static void init(Context context) {
}
}
TestApplication中的调用:
public class TestApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
SdkManager.init(this);
}
}
需要注意的是:SdkManager在debug和release中被调用的方法和参数是需要一致的,而且release下的代码的import需要自己手动添加。
2、module依赖时差异化构建的错误
例如:
主项目中引用了一个library:
compile project(':testLibrary')
在testLibrary中又引用了:
debugCompile 'com.facebook.stetho:stetho:1.5.0'
此时如果在主项目中的进行初始化并且进行debug运行的时候会发现如下错误:
这是主工程依赖子module时默认依赖的是子module的release版本,那么library中的stetho引用为debugCompile,所以运行的时候就找不到类了,哪怕是主项目中的依赖改为:
debugCompile project(':testLibrary')
debug运行的时候也是会出现找不到类的错误
此时的解决办法是:让主工程在debug版本下依赖module的debug版本,在release下依赖module的release版本即可。
第一步:在module的build.gradle文件中,增加 publishNonDefault true ,让module不再按默认只构建release版本
android {
...
publishNonDefault true
}
dependencies {
...
debugCompile 'com.facebook.stetho:stetho:1.5.0'
}
第二步:
在主工程的build.gradle中,增加如下代码:
String test;
android {
...
buildTypes {
release {
...
test = "release"
}
debug{
test = "debug"
}
}
}
dependencies {
...
compile project(path:':testLibrary',configuration:test)
}
这样在debug下就能运行了。但是这个时候发现打release包的时候stetho还是被打包进去了,有知道的请告知下。