簡介
我們在使用Android Studio開發安卓項目時,會引用到官方 sdk 或者他人的庫,方法都是在 module 的 build.gradle文件中添加如下代碼:
implementation 'com.android.support:appcompat-v7:28.0.0'
一行代碼就可以把我們想使用的庫引入到了項目中。然而一般情況下我們要想引入自己開發的庫,則是將整個 module 導入項目,並在需要引用該module的module的build.gradle文件中添加如下代碼:
implementation project(':lib_utils')
如果項目較大,多人在同一個項目目錄下編寫代碼既不優雅也不安全。
假如我們也只需要在 build.gradle 文件中使用一行 implementation 代碼就能實現引入自己或同事的 module 模塊,而不需要關心這個 module 放在哪裏,那豈不是很開心。
發佈
搭建Maven私服
搭建maven私服有多種方式(例如JFrog的Artifactory、sonatype社區的nexus),我們使用Nexus。
具體搭建過程不做介紹。
上傳庫到Nexus
添加配置信息
-
在項目根目錄local.properties添加
MAVEN_REPOSITORY_RELEASE_PATH=http://xxx.xxx.xxx.xxx:xxxx/repository/maven-releases/
PACKAGE_TYPE=aar
GROUP_ID=per.goweii
NEXUS_USERNAME=Nexus用戶名
NEXUS_PASSWORD=Nexus密碼
-
在庫Model的gradle.properties添加
ARTIFACT_ID=庫名
VERSION_NAME=庫版本號
創建上傳gradle文件
-
在項目根目錄新建maven.gradle
apply plugin: 'maven'
uploadArchives {
repositories {
mavenDeployer {
def properties = new Properties()
def inputStream = project.rootProject.file('local.properties').newDataInputStream()
properties.load(inputStream)
def MAVEN_REPOSITORY_RELEASE_PATH = properties.getProperty('MAVEN_REPOSITORY_RELEASE_PATH')
def NEXUS_USERNAME = properties.getProperty('NEXUS_USERNAME')
def NEXUS_PASSWORD = properties.getProperty('NEXUS_PASSWORD')
def PACKAGE_TYPE = properties.getProperty('PACKAGE_TYPE')
def GROUP_ID = properties.getProperty('GROUP_ID')
repository(url: MAVEN_REPOSITORY_RELEASE_PATH) {
authentication(userName: NEXUS_USERNAME, password: NEXUS_PASSWORD)
}
pom.project {
packaging PACKAGE_TYPE
groupId GROUP_ID
artifactId ARTIFACT_ID
version VERSION_NAME
}
}
}
}
-
在需要上傳的Model的build.gradle添加
apply from:'../maven.gradle'
開始上傳
確認庫配置信息(尤其是版本名)無誤後Sync項目,然後在Android Studio的Terminal中輸入如下命令開始上傳。上傳成功會有SUCCESS提示。
- Windows系統
gradlew uploadArchives
- Mac系統
./gradlew uploadArchives
引用
添加倉庫地址
在Project的build.gradle中添加倉庫地址
maven { url 'MAVEN_REPOSITORY_RELEASE_PATH' }
添加庫依賴
在Model的build.gradle中添加庫依賴
implementation 'GROUP_ID:ARTIFACT_ID:VERSION_NAME'