由于公司項(xiàng)目多,且都依賴于一個(gè)公共Library,導(dǎo)致Library有變動(dòng)所有的被依賴者都需要重新修改、構(gòu)建,很繁瑣。而用Maven管理,只需添加如下的一行代碼到模塊的build.gradle文件中,就可以輕松解決問題了。
//adnroid 3.0以下使用compile,3.0及其以上可以使用api/implementation
//api/implementation的區(qū)別可以自行百度
dependencies {
implementation 'com.android.library:lib:+'
}
以下為筆者本地配置,用的是Mac系統(tǒng)
配置Nexus
-
下載Nexus 官網(wǎng)地址
Nexus示例.png
筆者下載的是 nexus-2.14.8-01-bundle版本 -
解壓后,即可以在安裝目錄下看到兩個(gè)文件夾,主要是Nexus運(yùn)行環(huán)境和存儲Library。上傳的Library會存放在下圖storage下對應(yīng)的文件夾中。
Nexus_Path.png -
命令行cd到nexus-2.14.8-01-bundle/bin目錄下,使用命令
nexus start啟動(dòng)Nexus。
Nexus_start.png -
如果啟動(dòng)成功,打開網(wǎng)頁,訪問 http://localhost:8081/nexus/
默認(rèn)用戶名admin,密碼admin123Nexus_login.png -
登陸后,在左側(cè)邊欄點(diǎn)擊
Repositories。點(diǎn)擊Add,選擇Hosted Repository添加私有倉庫。
Nexus_repository.png -
填寫自己的
Repository ID,Repository Name,把Deploymen Policy勾選為Allow Redeploy,然后其他默認(rèn)就可以,點(diǎn)擊保存。
Nexus_create.png
然后在列表中就可以找到我們的庫在本地的地址http://localhost:8081/nexus/content/repositories/lib/,這個(gè)地址在后面會用到
Nexus_lib.png
配置Gradle
- 在需要發(fā)布的模塊下新建一個(gè)
nexus_maven_push.gradle,與build.gradle同層級
Gradle.png -
nexus_maven_push.gradle中主要配置的內(nèi)容有:url,authentication以及pom.project里面的信息
apply plugin: 'maven'
configurations {
deployerJars
}
repositories {
mavenCentral()
}
uploadArchives {
repositories {
mavenDeployer {
repository(url: "http://localhost:8081/nexus/content/repositories/lib/") {
authentication(userName: "admin", password: "admin123")
}
pom.project {
name 'test'
version '1.0.0'
artifactId 'lib'
groupId 'com.android.library'
packaging 'aar'
description 'library for android'
}
}
}
}
- 在該模塊下的
build.gradle文件最后,添加
apply from: 'nexus_maven.gradle' -
在項(xiàng)目同步之后,就可以上傳了
Gradle_upload.png
選擇uploadArchives,如果項(xiàng)目沒有什么問題的話,則會提示BUILD SUCCESSFUL。
刷新網(wǎng)頁,可以看到Library已經(jīng)成功上傳
Gradle_upload_success.png
Library使用
- 在項(xiàng)目的
build.gradle里面聲明私服的地址:
allprojects {
repositories {
maven {
url 'http://localhost:8081/nexus/content/repositories/lib/'
}
jcenter()
google()
}
}
- 在需要使用該模塊的
build.gradle文件中,添加項(xiàng)目依賴。
dependencies {
implementation 'com.android.library:lib:+'
}
使用+是為了同步時(shí),都會獲取到最新的版本。當(dāng)然固定版本號也是可以的。
dependencies {
implementation 'com.android.library:lib:1.0.0'
}
- 這里的組成和提交的
pom.project的信息有關(guān)。
pom.png
注意:上傳所用Android Studio的Gradle版本,需要與下載所用的一致。
關(guān)于Gradle緩存
在執(zhí)行過一次Gradle的同步之后,Gradle會把對應(yīng)的Library的文件下載在本地,之后會直接使用。所以當(dāng)我們刪除舊的Library,用同樣的pom.project信息重新上傳一個(gè)新的Library時(shí),執(zhí)行Gradle同步,并不會更新最新的Library下來。這個(gè)時(shí)候可以到倉庫存儲路徑下把對應(yīng)的Library文件刪除。
一般來說,
Mac系統(tǒng)默認(rèn)下載到:/Users/(用戶名)/.gradle/caches/modules-2/files-2.1
Windows系統(tǒng)默認(rèn)下載到:C:\Users(用戶名).gradle\caches\modules-2\files-2.1










