第一部分:异常情况处理
按照第二部分正常引入第三方jar包正常使用之后,项目若引入新的第三方库后,出现引入的jar包资源又变红,编译不通过的异常。解决方式:手动将xxx.iml 文件中的 <orderEntry type="jdk" jdkName="Android API 30 Platform" jdkType="Android SDK" />移动到文件最后即可。
第二部分:正常引入jar包核心步骤
1、引入第三方jar包
provided files('libs/framework.jar')
2、使用如下代码提高导入jar包优先级,将系统jar包自动至于最后位置
android{
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
Set<File> fileSet = options.bootstrapClasspath.getFiles()
List<File> newFileList = new ArrayList<>();
//"../framework.jar" 为相对位置,需要参照着修改,或者用绝对位置
newFileList.add(new File("libs/framework.jar"))
newFileList.addAll(fileSet)
options.bootstrapClasspath = files(newFileList.toArray())
}
}
}
preBuild {
doLast {
//此处文件名根据实际情况修改:
def imlFile = file("../.idea/modules/app/My_Application.app.iml")
// def imlFile = file(project.name + ".iml")
try {
def parsedXml = (new XmlParser()).parse(imlFile)
def jdkNode = parsedXml.component[1].orderEntry.find { it.'@type' == 'jdk' }
parsedXml.component[1].remove(jdkNode)
def sdkString = "Android API " + android.compileSdkVersion.substring("android-".length()) + " Platform"
new Node(parsedXml.component[1], 'orderEntry', ['type': 'jdk', 'jdkName': sdkString, 'jdkType': 'Android SDK'])
groovy.xml.XmlUtil.serialize(parsedXml, new FileOutputStream(imlFile))
} catch (FileNotFoundException e) {
// nop, iml not found编译之后
println "no iml found"
}
}
}