由于公司項(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-2.14.8-01-bundle版本 -
解壓后衫樊,即可以在安裝目錄下看到兩個(gè)文件夾,主要是Nexus運(yùn)行環(huán)境和存儲(chǔ)Library。上傳的Library會(huì)存放在下圖storage下對(duì)應(yīng)的文件夾中科侈。
-
命令行cd到nexus-2.14.8-01-bundle/bin目錄下载佳,使用命令
nexus start
啟動(dòng)Nexus。
-
如果啟動(dòng)成功臀栈,打開網(wǎng)頁蔫慧,訪問 http://localhost:8081/nexus/
默認(rèn)用戶名admin,密碼admin123 -
登陸后权薯,在左側(cè)邊欄點(diǎn)擊
Repositories
姑躲。點(diǎn)擊Add
,選擇Hosted Repository
添加私有倉庫。
-
填寫自己的
Repository ID
,Repository Name
,把Deploymen Policy
勾選為Allow Redeploy
盟蚣,然后其他默認(rèn)就可以黍析,點(diǎn)擊保存。
然后在列表中就可以找到我們的庫在本地的地址http://localhost:8081/nexus/content/repositories/lib/
,這個(gè)地址在后面會(huì)用到
配置Gradle
- 在需要發(fā)布的模塊下新建一個(gè)
nexus_maven_push.gradle
,與build.gradle
同層級(jí)
-
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)目同步之后屎开,就可以上傳了
選擇uploadArchives,如果項(xiàng)目沒有什么問題的話阐枣,則會(huì)提示BUILD SUCCESSFUL。
刷新網(wǎng)頁奄抽,可以看到Library已經(jīng)成功上傳
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í)逞度,都會(huì)獲取到最新的版本额划。當(dāng)然固定版本號(hào)也是可以的。
dependencies {
implementation 'com.android.library:lib:1.0.0'
}
- 這里的組成和提交的
pom.project
的信息有關(guān)档泽。
注意:上傳所用Android Studio的Gradle版本俊戳,需要與下載所用的一致。
關(guān)于Gradle緩存
在執(zhí)行過一次Gradle的同步之后茁瘦,Gradle會(huì)把對(duì)應(yīng)的Library的文件下載在本地品抽,之后會(huì)直接使用。所以當(dāng)我們刪除舊的Library甜熔,用同樣的pom.project信息重新上傳一個(gè)新的Library時(shí),執(zhí)行Gradle同步突倍,并不會(huì)更新最新的Library下來腔稀。這個(gè)時(shí)候可以到倉庫存儲(chǔ)路徑下把對(duì)應(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