作者個(gè)人網(wǎng)站:http://www.harddone.com
很多時(shí)候,Android Studio中所創(chuàng)建的工程,會(huì)依賴一個(gè)或多個(gè)Module。Module 生成的AAR庫(kù),可以上傳到maven或者私服Nexus作為公用的SDK。Gradle子工程之間通過(guò)?compile/implementation project(":XXX")這種方式依賴是非常便利的,但是這樣的時(shí)候,如果用uploadArchives上傳AAR到Maven,生成的pom.xml是不正確的,以致于在工程中依賴我們上傳的庫(kù)時(shí),無(wú)法找到它如下圖所示:

所以本文記錄在這種情況下,如何上傳AAR到Maven或Nexus.
一. 前提:
本文以上傳到Nexus為例說(shuō)明,如何本地配置Nexus,請(qǐng)參見(jiàn)這里。
二. 具體步驟
我們以測(cè)試demo的創(chuàng)建過(guò)程進(jìn)行詳細(xì)說(shuō)明。工程結(jié)構(gòu)如圖所示:其中mylibrary依賴于common庫(kù)

2.1 創(chuàng)建Android工程,新建module:common和mylibrary
2.2 配置project級(jí) gradle.properties:

2.3 在common module下,新建gradle.properties文件,用來(lái)聲明該module的名稱和版本號(hào)。

2.4 mylibrary module下進(jìn)行同樣的步驟,參見(jiàn)上一步2.3.
2.5 創(chuàng)建上傳aar的gradle文件,實(shí)現(xiàn)上傳的task.?
在project級(jí)目錄下,新建mvn_push.gradle文件
apply plugin: 'maven'
def getRepositoryUsername() {
? ? return hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : ""
}
def getRepositoryPassword() {
? ? return hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : ""
}
uploadArchives {
? ? configuration = configurations.archives
? ? repositories {
? ? ? ? mavenDeployer {
? ? ? ? ? ? repository(url: NEXUS_URL) {
? ? ? ? ? ? ? ? authentication(userName: getRepositoryUsername(), password: getRepositoryPassword())
? ? ? ? ? ? ? ? pom.groupId = GROUP_ID
? ? ? ? ? ? ? ? pom.artifactId = ARTIFACT_ID
? ? ? ? ? ? ? ? pom.version = VERSION
? ? ? ? ? ? }
? ? ? ? ? ? pom.whenConfigured { pom ->
? ? ? ? ? ? ? ? pom.dependencies.forEach { dep ->
? ? ? ? ? ? ? ? ? ? if (dep.getVersion() == "unspecified") {
? ? ? ? ? ? ? ? ? ? ? ? println("--modify the dependenies module in pom.xml--->>" + dep.getArtifactId())
? ? ? ? ? ? ? ? ? ? ? ? dep.setGroupId(GROUP_ID)
? ? ? ? ? ? ? ? ? ? ? ? dep.setVersion(VERSION)
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
2.6 引用mvp_push.gradle
分別在common 和 mylibrary 的build.gradle中添加如下代碼:
apply from:'../mvn_push.gradle'
如圖所示:

3. 上傳common庫(kù)和mylibrary庫(kù)
執(zhí)行 gradlew upload 或者 分別執(zhí)行uploadArchives task,完成后即可在nexus倉(cāng)庫(kù)中查看。

4.引用上傳的庫(kù)
4.1 在project的build.gradle中添加如下配置,該url即nexus倉(cāng)庫(kù)的位置:
maven { url"http://localhost:8081/repository/android/" }

4.2 在app的build.gradle中添加依賴
dependencies {
?????implementation fileTree(dir:'libs',include: ['*.jar'])
????implementation'com.android.support:appcompat-v7:27.1.1'
? ? implementation'com.android.support.constraint:constraint-layout:1.1.2'
? ? testImplementation'junit:junit:4.12'
? ? androidTestImplementation'com.android.support.test:runner:1.0.2'
? ? androidTestImplementation'com.android.support.test.espresso:espresso-core:3.0.2'
? ? implementation'test.com.ssc.libs:mylibrary:1.0.0'
? ? implementation'test.com.ssc.libs:common:1.0.0'
}
以上。
源碼地址:https://github.com/LazyBonesLZ/NexusTest,demo中配置的nexus倉(cāng)庫(kù)url是我本地服務(wù)地址,請(qǐng)改成你創(chuàng)建好的nexus倉(cāng)庫(kù)地址。
參考: