AndroidStudio使用maven-publish发布aar至mavencentral中央仓库

AndroidStudio使用maven-publish发布aar至mavencentral中央仓库

  1. 注册【sonatype】账号
  2. 创建Group ID
  3. 下载安装gnupg
  4. 创建生成密钥
  5. 配置maven-publish打包推送aar
  6. 发布到mavencentral中央仓库
  7. 从mavencentral中央仓库依赖使用发布的AAR

1、注册【sonatype】

打开注册地址,如图填写自己的信息,点击signup进行注册。密码要求的比较严格,我一般都是设置的包含大小写字母、数字、符号。密码中也不能出现用户名。
sonatype注册

2、创建Group ID

第一步注册成功之后,直接登录。
首先点击【新建】创建问题。项目及问题类型,选择如下图。
新建project
create

点击【新建】提交成功之后,会产生一个问题工单,等待工单的处理。
使用github的话,一般都是让在对应的GitHub创建一个指定名称(OSSRH-****)的public存储库,用于验证所填写的 io.github.** 是否是自己的。

当在GitHub上创建完对应的public存储库以后,需要点击【备注】对工单进行回复处理。一般用英文随便回复两句,客气客气。
比如我用菜的抠脚的英文回复:(O(∩_∩)O哈哈~,总之让老外能看懂就行)

Hello, the repository has been created.
please check, thanks

一般回复完,等个几分钟,工单状态变成“已解决”,就说明我们的 Group ID 创建完成了,以后就可以向自己填写的Group ID下面发布了。

3、下载安装gnupg

由于maven-publish发布时需要签名,得下载安装gnupg。
我的电脑是Windows系统,这里就下载Gpg4win。根据自己的系统,自行选择对应版本。
安装完成即可。
GPG下载

检查是否安装成功,在控制台输入 gpg --version。能看到版本号就OK。

PS E:Android> gpg --version
gpg (GnuPG) 2.3.8
libgcrypt 1.10.1
Copyright (C) 2021 g10 Code GmbH
License GNU GPL-3.0-or-later <https://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Home: C:UsersAdministratorAppDataRoaminggnupg
Supported algorithms:
Pubkey: RSA, ELG, DSA, ECDH, ECDSA, EDDSA
Cipher: IDEA, 3DES, CAST5, BLOWFISH, AES, AES192, AES256, TWOFISH,
        CAMELLIA128, CAMELLIA192, CAMELLIA256
AEAD: EAX, OCB
Hash: SHA1, RIPEMD160, SHA256, SHA384, SHA512, SHA224
Compression: Uncompressed, ZIP, ZLIB, BZIP2

4、创建生成密钥

  1. 使用 gpg --full-generate-key 命令创建密钥
  2. Your selection? 填写 1 ,选择 RSA and RSA
  3. What keysize do you want? (3072) 默认3072,这里我们填写 4096
  4. Key is valid for? (0) 默认填 0,密钥不过期。
  5. Real name: 填写名称
  6. Email address: 自己邮箱
  7. Comment: 可以不填,直接回车
  8. Change (N)ame, ©omment, (E)mail or (O)kay/(Q)uit? 填写大写字母 O, 直接回车确定 。
  9. 耐心等待创建完成,可能需要十几秒时间。

过程中会弹窗提示输入密钥的密码,输入两次密码,确认保存即可。(这里的密码记录保存好,后面会用到)
密钥密码

完整示例如下:

PS E:Android> gpg --full-generate-key
gpg (GnuPG) 2.3.8; Copyright (C) 2021 g10 Code GmbH
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Please select what kind of key you want:
   (1) RSA and RSA
   (2) DSA and Elgamal
   (3) DSA (sign only)
   (4) RSA (sign only)
   (9) ECC (sign and encrypt) *default*
  (10) ECC (sign only)
  (14) Existing key from card
Your selection? 1
RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (3072) 4096
Requested keysize is 4096 bits
Please specify how long the key should be valid.
         0 = key does not expire
      <n>  = key expires in n days
      <n>w = key expires in n weeks
      <n>m = key expires in n months
      <n>y = key expires in n years
Key is valid for? (0) 0
Key does not expire at all
Is this correct? (y/N) y

GnuPG needs to construct a user ID to identify your key.

Real name: mtjsoft1
Email address: mtjsoft3@gmail.com
Comment:
You selected this USER-ID:
    "mtjsoft1 <[email protected]>"

Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
gpg: revocation certificate stored as 'C:\Users\Administrator\AppData\Roaming\gnupg\openpgp-revocs.d\BA571B36612AED30A650910F51CAEFFD7F1790E5.rev'
public and secret key created and signed.

pub   rsa4096 2022-11-26 [SC]
      BA571B36612AED30A650910F51CAEFFD7F1790E5
uid                      mtjsoft1 <mtjsoft3@gmail.com>
sub   rsa4096 2022-11-26 [E]

最后我们可以使用 gpg --list-keys 命令查看创建的密钥。

PS E:Android> gpg --list-keys
C:UsersAdministratorAppDataRoaminggnupgpubring.kbx
--------------------------------------------------------
pub   rsa4096 2022-11-24 [SC]
      BF81E3FF1A632D36CE42C7137396A6CBC4693B36
uid           [ultimate] readcard <mtjsoft3@gmail.com>
sub   rsa4096 2022-11-24 [E]

pub   rsa4096 2022-11-26 [SC]
      BA571B36612AED30A650910F51CAEFFD7F1790E5
uid           [ultimate] mtjsoft1 <mtjsoft3@gmail.com>
sub   rsa4096 2022-11-26 [E]

发布证书,备份私钥

打开安装的 gnupg 软件

  1. 复制 密钥ID的后八位,发布aar时需要用到。
  2. 右键证书,在服务器上发布证书。如下图 步骤2。
  3. 右键证书,备份私钥,后缀名改成 .gpg。保存好,发布aar时需要使用到此文件。

5. 配置maven-publish打包推送aar

  1. 在根目录的 local.properties 中添加如下配置信息
# 要发布的版本名(以 SNAPSHOT 结尾的,为快照版本 如: 3.1.0-SNAPSHOTPUBLISH_VERSION=3.1.0
# 步骤2中创建的 GROUP_ID
PUBLISH_GROUP_ID=io.github.**
# 名称
PUBLISH_ARTIFACT_ID=FaceSDk
# 上面三个参数配置完。一般通过mavencentral引用aar的依赖时,就是这样子了
# implementation "io.github.**:FaceSDk:3.1.0"

# 步骤4中 密钥ID的后8位
signing.keyId=C4693B36
# 步骤4中 创建密钥时填写的密码
signing.password=mima
# 步骤4中 备份私钥保存的文件路径
signing.secretKeyRingFile=E:\Android\0xC4693B36_SECRET.gpg

# 步骤1中 注册sonatype的用户名与密码
ossrhUsername=mtjsoft
ossrhPassword=mima
  1. 项目根目录创建 publish-mavencentral.gradle。直接复制修改几处注释的地方即可。
apply plugin: 'maven-publish'
apply plugin: 'signing'

// 此处不需修改,下面会读取 local.properties 中配置的信息
ext["PUBLISH_VERSION"] = '' //发布的版本
ext["PUBLISH_GROUP_ID"] = ''  //分组ID
ext["PUBLISH_ARTIFACT_ID"] = '' //
ext["signing.keyId"] = '' //签名的密钥后8位
ext["signing.password"] = ''  //签名设置的密码
ext["signing.secretKeyRingFile"] = '' //生成的secring.gpg文件目录
ext["ossrhUsername"] = ''  //sonatype用户名
ext["ossrhPassword"] = ''  //sonatype密码
// 遍历赋值
File secretPropsFile = project.rootProject.file('local.properties')
if (secretPropsFile.exists()) {
    println "Found secret props file, loading props"
    Properties p = new Properties()
    p.load(new FileInputStream(secretPropsFile))
    p.each { name, value ->
        ext[name] = value
    }
} else {
    println "No props file, loading env vars"
}

afterEvaluate {
    publishing {
        repositories {
            maven {
                //推送至远端的中央仓库,一旦发布release中央仓库版本,旧版本无法修改
                //一般都在  暂存库  中进行测试,然后确认无误后再发布到 release中央仓库
                allowInsecureProtocol = false
                name = PUBLISH_ARTIFACT_ID
                // 暂存库
                def releasesRepoUrl = "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/"
                // 快照库(版本名以 SNAPSHOT 结尾,就推送至快照库)
                def snapshotsRepoUrl = "https://s01.oss.sonatype.org/content/repositories/snapshots/"
                url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl

                credentials {
                    username ossrhUsername
                    password ossrhPassword
                }
            }
            maven {
                // 推送至本地存储库,本机测试的时候可以用
                allowInsecureProtocol = false
                name = 'Local'
                url = uri('../ZrgkLocalRepo')
            }
        }
        publications {
            release(MavenPublication) {
                println("publish-maven Log-------> PUBLISH_GROUP_ID: $PUBLISH_GROUP_ID; PUBLISH_ARTIFACT_ID: $PUBLISH_ARTIFACT_ID; PUBLISH_VERSION: $PUBLISH_VERSION")

                groupId PUBLISH_GROUP_ID
                artifactId PUBLISH_ARTIFACT_ID
                version PUBLISH_VERSION

                // 生成的 aar 路径,修改成自己的aar地址名称
                artifact("$buildDir/outputs/aar/face-release.aar")
                
                // 如果需要将源代码一起打包进aar,就打开此注释。
                //artifact androidSourcesJar

                pom {
                    name = PUBLISH_ARTIFACT_ID
                    description = '这是一段SDK的项目描述' //项目描述
                    url = 'https://github.com/***/***' //项目github链接
                    licenses {
                        license {
                            //协议类型,一般默认Apache License2.0的话不用改:
                            name = 'The Apache License, Version 2.0'
                            url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
                        }
                    }
                    developers {
                        developer {
                            // 修改自己对应的用户名、邮箱
                            id = 'mtj' //你的sonatype用户名
                            name = 'mtj' //你的sonatype用户名
                            email = 'mtj@gmail.com' //你的sonatype注册邮箱
                        }
                    }
                    // Version control info, if you're using GitHub, follow the format as seen here
                    scm {
                        //修改成你的Git地址:
                        connection = 'scm:git@github.com:**/**.git'
                        developerConnection = 'scm:[email protected]:**/**.git'
                        //分支地址:
                        url = 'https://github.com/**/**'
                    }

                    withXml {
                        def dependenciesNode = asNode().appendNode("dependencies")
                        configurations.implementation.allDependencies.forEach() {
                            Dependency dependency ->
                                if (dependency.version != "unspecified" && dependency.name != "unspecified") {
                                    def dependencyNode = dependenciesNode.appendNode('dependency')
                                    dependencyNode.appendNode('groupId', dependency.group)
                                    dependencyNode.appendNode('artifactId', dependency.name)
                                    dependencyNode.appendNode('version', dependency.version)
                                }
                        }
                    }
                }
            }
        }
    }
    signing {
        sign publishing.publications
    }
}

// 生成文档注释
task androidJavadocs(type: Javadoc) {
    // 设置源码所在的位置
    source = android.sourceSets.main.java.srcDirs
}

// 将文档打包成jar,生成javadoc.jar
task androidJavadocsJar(type: Jar) {
    // 指定文档名称
    archiveClassifier.set('javadoc')
    from androidJavadocs.destinationDir
}

// 将源码打包 ,生成sources.jar
task androidSourcesJar(type: Jar) {
    archiveClassifier.set('sources')
    from android.sourceSets.main.java.srcDirs

    exclude "**/R.class"
    exclude "**/BuildConfig.class"
}

//配置需要上传到maven仓库的文件
artifacts {
    archives androidSourcesJar //将源码打包进aar,这样使用方可以看到方法注释.
    archives androidJavadocsJar //将注释打包进aar
}
  1. 在AAR module 的 build.gradle 中引入创建的 publish-mavencentral.gradle。示例如下:
plugins {
    id 'com.android.library'
    id 'kotlin-android'
    id 'kotlin-kapt'
}
// 必须在 android 上面
apply from: '../publish-mavencentral.gradle'

android {
    compileSdkVersion 30
    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 30
        versionCode 1
        // 版本名字直接使用配置的 PUBLISH_VERSION
        versionName PUBLISH_VERSION
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        consumerProguardFiles "consumer-rules.pro"
    }
}
  • sync gradle。
  • 点击开发工具右侧 “Gradle”,如下图 1
  • 编译打包aar,如选图 2,等待编译打包完成。
  • 推送到mavenCentral暂存库,如下图 3
    打包推送aar

6. 发布到mavencentral中央仓库

登录Nexus Repository Manager
输入步骤 1 注册的账号密码
登录

  1. 点击左侧 暂存库,如下图 1 。即可在列表中看到自己推送上来的aar,如果没有,就点击 “Refresh”刷新几次。
  2. 到目前为止,aar还处在暂存库中。如果测试库一切正常后,我们可以勾选上。然后点击 “Close”,如下图 2 。
  3. 稍等片刻后,刷新几次。可以看到状态已改变。再次勾选上,然后点击 “Release”,如下图 3 。发布AAR。
    注意,一旦发布Release版本之后,这个版本就不能被修改删除了,只能再发新版本。这也是合理的,试想你正在使用的版本库,突然被别人删了,那就不好了
    发布

7. 从mavencentral中央仓库依赖使用发布的AAR

好了,我们的aar终于发布完成,可以提供给其他人去使用了。

  1. 在项目根目录 build.gradle 配置:
allprojects {
    repositories {
        google()
        jcenter()
        // 增加mavenCentral中央仓库
        mavenCentral()
    }
}
  1. 在 module 的 build.gradle 配置:
dependencies {
    // 规则就是在 local.properties 中配置的
    // PUBLISH_GROUP_ID:PUBLISH_ARTIFACT_ID:PUBLISH_VERSION
    implementation "io.github.**:**:3.1.0"
}

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码

)">
< <上一篇
下一篇>>