subprojects 和 allprojects 的区别,
先给出结论:
include ':app',':lib'
在build.gradle中写入:
allprojects {
tasks.create('hello') {
doLast {
task ->
print "project name is $task.project.name \n"
}
}
}
测试一下allprojects的范围,打开控制台,并切换到新建的根目录,执行gradle -q hello命令,执行结果:
bogon:test_gradle mq$ gradle -q hello
project name is test_gradle
project name is app
project name is lib
再来测试下subprojects的作用域,打开build.gradle继续写入:
allprojects {
tasks.create('hello') {
doLast {
task ->
print "project name is $task.project.name \n"
}
}
}
subprojects {
hello << {
print "here is subprojects \n"
}
}
可以看到我们在下面新加了subprojects,并通过之前建的task任务hello输出了一段字符串,继续执行命令gradle -q hello,执行结果:
bogon:test_gradle mq$ gradle -q hello
project name is test_gradle
project name is app
here is subprojects
project name is lib
here is subprojects
可以看到只有只有根目录下面没有subprojects中task的输出,这也印证了我们上面的结论:
allprojects是对所有project的配置,包括Root Project;
而subprojects是对所有Child Project的配置。
进入Child Project目录下,新建一个build.gradle文件,写入:
hello.doLast {
print " —— I'm the app project \n"
}
继续执行命令gradle -q hello,执行结果:
bogon:test_gradle mq$ gradle -q hello
project name is test_gradle
project name is app
here is subprojects
—— I'm the app project
project name is lib
here is subprojects
在rootProject下的build.gradle中,buildscript的repositories和allprojects的repositories有什么区别?如下:
//build.gradle
buildscript {
repositories {
jcenter()
google()
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
}
}
allprojects {
repositories {
jcenter()
google()
maven {
url "http://maven.xxxxxxxx/xxxxx"
}
}
}
1、buildscript里是gradle脚本执行所需依赖,如上所示对应的是maven库和插件 。
2、allprojects里是项目本身需要的依赖,
比如代码中某个类是打包到maven私有库中的,那么在allprojects—>repositories中需要配置maven私有库,而不是buildscript中,不然找不到。
在安卓开发时,本地同时跑了中台,由于每天重连wifi分配的局域网IP都会变化,这导致打包调试时总是需要改IP地址,通过gradle脚本自动获取本机IP,然后动态流入到对应的参数链接中,之后就不用再去改代码了
此处以项目为例:首先在build.gradle中定义获取IP的方法
static def getIP() { InetAddress result = null; Enumerationinterfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { Enumeration addresses = interfaces.nextElement().getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (!address.isLoopbackAddress()) { if (address.isSiteLocalAddress()) { return address.getHostAddress(); } else if (result == null) { result = address; } } } } return (result != null ? result : InetAddress.getLocalHost()).getHostAddress(); }
然后调用方法获取IP,流入到BuildConfig或者是渠道信息中,此处以BuildConfig为例
android { …… defaultConfig { …… buildConfigField("String", "IPAddress", "\"http://" + getIP() + ":8080/Service/\"") } }
此时IPAddress被注入到BuildConfig的静态变量中,在项目的网络配置NetworkConfig中使用
static { switch (BuildConfig.FLAVOR) { case "local":{ BASE_URL = BuildConfig.IPAddress; YUNWEI_URL = YUNWEI_URL_TEST; UPDATE_URL = UPDATE_URL_TEST; break; } case "dev":…… case "check": …… } }