引入aar的沖突無所不在,通過遠程依賴maven的包可以通過exclude
關鍵字搭配module
和group
去除某個組,沒辦法去除具體的類。
那么如果是單獨的aar包,想要排除aar下classes.jar包里的某個單獨的包或者類怎么辦?
需要接入的jar包已經帶了騰訊X5核心,當前依賴的已經包含X5核心,沖突又該如何解決呢?
當前的gradle腳本(項目鏈接:https://github.com/luohongxfb/ExcludeAar )可以解決。
1 效果展示
如excludelib/libs/exampleAAR.aar,左邊是未去除的包結構,右邊是去除com.baidu
之后的:
如excludelib/libs/exampleJAR.jar:
2 如何使用
(1)將需要排除的aar或者jar包放在excludelib/libs下。
(2)更改excludelib/build.gradle
//需要排除的aar或者jar。(替換成需要排除的)
artifacts.add("exclude", file('libs/exampleAAR.aar'))
artifacts.add("exclude", file('libs/exampleJAR.jar'))
(3)設置排除規則 如果您需要排除aar,那么請更改excludelib/excludeAar.gradle;如果您需要排除jar,那么請更改excludelib/excludeJar.gradle
//需要排除的包名
def excludePackages = ['com.baidu']
//需要排除的類(需要全類名)
def excludeClasses = []
(4)運行排除任務
排除后生成的aar在excludelib/build/excludeaar下,排除后生成的jar位于excludelib/build/excludejar。
然后就可以愉快的使用啦~
3 如何實現的
aar排除步驟:
1、獲取到需要排除的原始AAR包
2、解壓AAR包(zipTree配合Task Copy)
3、解壓AAR包中的class.jar(zipTree配合Task Copy)
4、按照排除規則對解壓的class.jar重新打包(Task Jar)
5、重新打包成AAR包(Task Zip)
jar排除步驟
1、獲取到需要排除的原始jar包
2、解壓jar包(zipTree配合Task Copy)
3、按照排除規則對解壓的jar重新打包(Task Jar)
解壓AAR/JAR包
task unZipAar(type: Copy) {
def zipFile = getDefaultAar()
def outputDir = unZipAarFile
from zipTree(zipFile)
into outputDir
}
主要原理:zipTree配合Copy,實現解壓。
Copy Task官方講解:https://docs.gradle.org/current/dsl/org.gradle.api.tasks.Copy.html
ziptree源碼主要解析:創建一個新的file tree包含原來zip的內容,可以配合Copy實現解壓。
public interface Project{
/**
* <p>Creates a new {@code FileTree} which contains the contents of the given ZIP file.
* You can combine this method with the {@link #copy(groovy.lang.Closure)}
* method to unzip a ZIP file
* @param zipPath The ZIP file. Evaluated as per {@link #file(Object)}.
* @return the file tree. Never returns null.
*/
FileTree zipTree(Object zipPath);
}
按照排除規則對解壓的jar重新打包(這個是重點)
task zipJar(type: Jar) {
baseName = 'classes'
from unZipJarFile
destinationDir unZipAarFile
exclude getExcludePackageRegex(excludePackages)
exclude getExcludeClassRegex(excludeClasses)
}
這個步驟就是把之前解壓的classes.jar文件,按照排除規則用Task Jar重新打包成jar文件。
Task Jar官方講解:https://docs.gradle.org/current/dsl/org.gradle.jvm.tasks.Jar.html
Property/Method | Description |
---|---|
baseName | 壓縮后的jar文件名。 |
from(sourcePaths) | 需要壓縮的目錄。 |
destinationDir | 壓縮后存放的目錄。 |
exclude(excludes) | 需要排除的文件。 |
重新打包成AAR包
task excludeAar(type: Zip) {
group 'ex'
description '生成一個排除之后的aar包'
baseName excludeAarName
extension "aar"
from unZipAarFile
destinationDir excludeAarFile
}
對classes.jar處理完成的aar重打包,主要用到Task Zip。
Task Zip官方講解:https://docs.gradle.org/current/dsl/org.gradle.api.tasks.bundling.Zip.html
Property/Method | Description |
---|---|
group | setGroup(String group) 將當前的Task設置到指定組。 |
description | setDescription(@Nullable String description) Task描述。 |
baseName | 壓縮后的aar文件名。 |
extension | 壓縮后的文件擴展名。 |
from(sourcePaths) | 需要壓縮的目錄。 |
destinationDir | 壓縮后存放的目錄。 |
感謝Siy:https://blog.csdn.net/baidu_34012226/article/details/80104771