一、首先在module的build.gradle中添加以下代码,此段代码的目的是为了编译时动态的修改iml文件,将androidSutdio默认的Android SDK优先级调整到最后,以使我们自己的frameworks.jar的优先级提高,这样在代码加载时则会根据优先级进行加载,可以解决代码报红的问题
apply plugin: 'com.android.application'
// place in first line of gradle.
import groovy.xml.XmlUtil
// not contained in any attribute, put it in the outermost layer
// make SDK directory's android.jar set in libs behind
preBuild {
doLast {
def imlFile = file("D:\\workFiles\\androidProject\\CarServiceProject\\.idea\\modules\\car-lib\\CarServiceProject.car-lib.iml") //这里是此module的iml文件路径,一定要写对
// def imlFile = file(project.name + ".iml")
println 'Change ' + imlFile.name + ' order'
try {
def parseXml = new XmlParser().parse(imlFile)
def jdkNode = parseXml.component[1].orderEntry.find { it.'@type' == 'jdk' }
parseXml.component[1].remove(jdkNode)
def sdkString = "Android API " + android.compileSdkVersion.substring("android-".length()) + " Platform"
println 'sdkString ' + sdkString + ' '
new Node(parseXml.component[1], 'orderEntry', ['type': 'jdk', 'jdkName': sdkString, 'jdkType': 'Android SDK'])
XmlUtil.serialize(parseXml, new FileOutputStream(imlFile))
} catch (FileNotFoundException e) {
//nop, iml not found.
println e.printStackTrace()
}
}
}
android {
...
...
}
dependencies {
...
...
}
二、在module的build.gradle中添加依赖的frameworks.jar
dependencies {
......
compileOnly files('../libs/frameworks.jar')
}
三、在project的build.gradle中添加以下代码,目的是为了编译时优先加载我们自己的jar,可以解决编译失败的问题
static def isWindowsOS() {
return true
}
allprojects {
repositories {
google()
jcenter()
}
if (isWindowsOS()){
tasks.withType(JavaCompile){
println("this os is windows")
options.compilerArgs.add('-Xbootclasspath/p:D:\\workFiles\\androidProject\\CarServiceProject\\libs\\frameworks.jar')//这里最好使用绝对路径,因为我使用相对路径怎么都不行
}
}else{
tasks.withType(JavaCompile){
println("this os is linux")
options.compilerArgs.add('-Xbootclasspath/p:libs/frameworks.jar')//linux的没有测试过,暂且先这样吧
}
}
}
转自https://www.cnblogs.com/huhe/p/15848891.html
|