在安卓開發中,咱們常常會在 build.gradle
中引入各類各樣的依賴輔助咱們進行開發,如經常使用的 okhttp 請求 Library:android
dependencies {
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
}
複製代碼
若是咱們開發了本身的通用 Library,怎麼讓別人能夠這樣使用呢,下面介紹一下怎麼將 Android Library 發佈到 Jcenter。git
Jcenter是一個 Bintray 維護的 Maven 倉庫,咱們能夠在 Android 項目根目錄的 build.gradle
中設置如下內容使用:github
buildscript {
repositories {
Jcenter()
}
}
allprojects {
repositories {
Jcenter()
}
}
複製代碼
在發佈以前,先要註冊 bintray 帳號。web
註冊免費的開源帳戶請點擊右邊白色的文字,不要點擊綠色按鈕。bash
填寫好用戶信息、郵箱後激活帳戶便可使用。app
若是是我的發佈 Library,直接新建倉庫便可maven
若是是團隊,能夠先創建一個組織,在組織下操做。gradle
在建立 Library 以前,須要先建立倉庫(Repository),Library 是在倉庫之下的。按照以下示例,建立 maven 類型的倉庫ui
建立好 maven 倉庫後,點擊進入 maven 倉庫,點擊 Add a Package
便可建立 Library,正常填寫信息便可,在建立 Library 以前,能夠先在 GitHub 上建立源代碼倉庫,在提交審覈時須要。spa
在 Edit Profile 中能夠查看到 API Key,這裏須要記錄 API Key,在後面上傳 Library 時會用到。
這裏咱們要使用 bintray-release: 上傳咱們的 Library。
首要要添加插件,在項目根目錄的 build.gradle
中添加 classpath 信息
buildscript {
repositories {
Jcenter()
}
dependencies {
classpath 'com.novoda:bintray-release:<latest-version>'
}
}
複製代碼
而後在源代碼 build.gradle
中添加配置
apply plugin: 'com.android.library'
apply plugin: 'com.novoda.bintray-release' // android.library 後
android {
compileSdkVersion 29
buildToolsVersion "29.0.0"
...
}
// 設置 publish 信息
publish {
userOrg = 'github' // 組織名稱,我的同用戶名
groupId = 'com.github.xxx'
artifactId = 'xxx-lib'
publishVersion = '1.0.0'
desc = 'lib desc'
website = 'https://xxx.com'
}
複製代碼
在 sync 完成後,在項目根目錄運行下面的命令上傳 Library 文件
./gradlew clean build bintrayUpload -PbintrayUser=你的用戶名 -PbintrayKey=這裏填寫剛剛保存的API Key -PdryRun=false
複製代碼
若是提示 BUILD SUCCESSFUL
即表示上傳成功,就能夠在你的倉庫下看見上傳的 Library。
上傳完 Library 後,咱們須要把 Library 同步到 Jcenter,方便他人使用。進入 Library 頁面,能夠在 Actions 選項中找到 Add to Jcenter 選項,點擊後,不用填寫任何信息,提交,等待管理員審批便可。
最後咱們就能夠像文章首部提到的那樣使用咱們的 Library 了:
// 添加 Jcenter 源
buildscript {
repositories {
Jcenter()
}
}
allprojects {
repositories {
Jcenter()
}
}
複製代碼
// 添加依賴
dependencies {
// 格式:implementation 'groupId:lib:version'
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
}
複製代碼