Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

把自己寫的 Android 庫發布到 JCenter:完整流程與踩坑記錄

編輯:關於 Android 程式設計

寫了一個自己覺得還不錯的組件,與其躺在本地硬盤裡,不如開源出去讓更多人用。這篇記錄把 Android Library 發布到 JCenter 的完整流程,包含每一步的配置文件和容易卡住的地方。

前期準備

先申請一個倉庫賬號(Bintray),註意項目 module 的類型必須是 android library,而不是 application。

一、引入插件

在工程根目錄的 build.gradle 中加入兩個 classpath:

classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.2'
classpath 'com.github.dcendents:android-maven-plugin:1.2'

個人建議這兩個插件的版本保持一致,避免出現難以定位的兼容問題。改完後根目錄的 build.gradle 大致如下:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.0'
        classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.2'
        classpath 'com.github.dcendents:android-maven-plugin:1.2'
        // NOTE: Do not place your application dependencies here;
        // they belong in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

二、創建 bintray.gradle

在根目錄下新建一個名為 bintray.gradle 的文件(名字必須完全一致):

group = PROJ_GROUP
version = PROJ_VERSION
project.archivesBaseName = PROJ_ARTIFACTID

apply plugin: 'com.jfrog.bintray'
apply plugin: 'maven-publish'

task sourcesJar(type: Jar) {
    from android.sourceSets.main.java.srcDirs
    classifier = 'sources'
}

task javadoc(type: Javadoc) {
    source = android.sourceSets.main.java.srcDirs
    classpath += configurations.compile
    classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
}

task javadocJar(type: Jar, dependsOn: javadoc) {
    classifier = 'javadoc'
    from javadoc.destinationDir
}

javadoc {
    options {
        encoding "UTF-8"
        charSet 'UTF-8'
        author true
        version true
        links "https://docs.oracle.com/javase/7/docs/api"
        title PROJ_ARTIFACTID
    }
}

artifacts {
    archives javadocJar
    archives sourcesJar
}

def pomConfig = {
    licenses {
        license {
            name "The Apache Software License, Version 2.0"
            url "https://www.apache.org/licenses/LICENSE-2.0.txt"
            distribution "repo"
        }
    }
    developers {
        developer {
            id DEVELOPER_ID
            name DEVELOPER_NAME
            email DEVELOPER_EMAIL
        }
    }
    // 這裡的引號後必須留一個空格,否則依賴生成不出來。
    // 原因是這裡的 dependencies 並不是 build.gradle 裡的 dependencies,
    // Gradle 會把它當成自身的 dependencies 處理。
    "dependencies " {
        // dependency {
        //     groupId "com.alibaba"
        //     artifactId "fastjson"
        //     version "1.2.6"
        // }
    }
}

publishing {
    publications {
        mavenJava(MavenPublication) {
            artifactId PROJ_ARTIFACTID
            pom {
                packaging 'aar'
            }
            pom.withXml {
                def root = asNode()
                root.appendNode('description', PROJ_DESCRIPTION)
                root.children().last() + pomConfig
            }
        }
    }
}

bintray {
    Properties properties = new Properties()
    properties.load(project.rootProject.file('local.properties').newDataInputStream())
    user = properties.getProperty('BINTRAY_USER')
    key = properties.getProperty('BINTRAY_KEY')
    configurations = ['archives']
    publications = ['mavenJava']
    publish = true
    pkg {
        repo = 'maven'
        name = PROJ_NAME
        desc = PROJ_DESCRIPTION
        websiteUrl = PROJ_WEBSITEURL
        issueTrackerUrl = PROJ_ISSUETRACKERURL
        vcsUrl = PROJ_VCSURL
        licenses = ['Apache-2.0']
        publicDownloadNumbers = true
    }
}

這個文件幾乎不需要修改。唯一要動的地方是:如果你要上傳的包依賴了其他三方庫,需要在下面這個塊中聲明,否則使用者的項目會缺少傳遞依賴:

"dependencies " {
    dependency {
        groupId "com.alibaba"
        artifactId "fastjson"
        version "1.2.6"
    }
}

這段配置的作用是把依賴信息寫進生成的 pom 文件,讓下游用戶自動拉取,含義一目了然。

三、模塊配置與賬號信息

在 library 模塊的 build.gradle 中配置簽名並引入 bintray.gradle:

apply plugin: 'com.android.library'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    signingConfigs {
        config {
            keyAlias 'guolei'
            keyPassword '123456'
            storeFile file('guolei.jks')
            storePassword '123456'
        }
    }

    defaultConfig {
        minSdkVersion 17
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.config
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

apply from: '../bintray.gradle'

注意 bintray.gradle 一定要放在文件最下面,因為它依賴 android 擴展已經配置完成。

接著配置賬號憑證。BINTRAY_USER 就是你的用戶名,BINTRAY_KEY 需要到網站上查看:點擊 Edit 進入個人設置,找到 API Key 一欄,點 Show 即可看到。

在根目錄的 local.properties 中寫入:

BINTRAY_KEY=e21c3f96df17xxxxxxxx
BINTRAY_USER=guolei1130

這對應 bintray.gradle 中的這段讀取邏輯。當然你也可以改這段代碼,把兩個屬性寫在任何你喜歡的位置,只是放在 local.properties 裡更安全,不會被誤提交到倉庫:

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
user = properties.getProperty('BINTRAY_USER')
key = properties.getProperty('BINTRAY_KEY')

最後點擊 Sync Now 完成同步。

四、生成產物並上傳

生成 aar 包

在 Gradle 面板中找到 build 任務,執行後會生成對應的 aar 包:

生成 javadocJar 與 sourcesJar

在模塊的 other tasks 中找到這兩個任務,分別執行。這一步一般不會出錯,如果報錯通常是 javadoc 註釋裡有語法問題。

生成 pom 文件

在 publish 分組中執行對應任務,第二個即可:

執行上傳

點擊 bintrayUpload。如果報錯,根據錯誤信息排查即可,絕大多數情況是身份驗證相關的問題——回頭檢查 BINTRAY_USER 與 BINTRAY_KEY 是否正確。

五、同步到 JCenter(需要審核)

上傳成功後,包會先進入你自己的 Maven 倉庫。此時打開包的詳情頁,點擊右側的 JCenter 入口:

選擇要導入的庫,提交後等待管理員審核通過,別人才能正常依賴你的庫:

最後看一眼成果

GitHub 地址記得填寫正確,方便使用者查看源碼和文檔。

整個流程走一遍下來,熟練之後其實很快。

幾點補充說明

需要提醒的是,JCenter 已於 2021 年停止接受新的發布,現存包仍可讀取但不再更新。今天要發布 Android 庫,主流選擇是 Maven Central(通過 Sonatype 的 OSSRH 或新的 Central Portal),配合 gradle-maven-publish-plugin 使用;GitHub Packages 也是一個可行的備選。

好消息是,本文中 90% 的概念都是通用的:group、artifact、version 這三個坐標概念不變,sources jar 與 javadoc jar 的要求不變,簽名與 POM 中聲明 LICENSE、developer 信息的要求不變,只是發佈目標和認證方式換了地方。理解了「一個庫需要哪些元數據才能被別人正確引用」,換平台就只是改配置的問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved