使用AndroidStudio最新版本(现在是2021年8月9日,版本为:Android Studio Arctic Fox 2020.3.1),创建一个库项目,在库项目的build.gradle文件前面添加maven-publish插件,如下:
- plugins {
- id 'com.android.library'
- id 'kotlin-android'
- id 'maven-publish'
- }
-
然后在文件的最后,添加如下内容:
- // 用于打包源代码的任务
- task androidSourcesJar(type: Jar) {
- archiveClassifier.set('sources')
- from android.sourceSets.main.java.srcDirs
- }
-
- // 用于把aar打包到maven仓库的任务
- afterEvaluate {
- publishing {
- publications {
- release(MavenPublication) {
- from components.release
- artifact androidSourcesJar
- groupId = 'cn.android666.contextholder' // 库的组织,使用域名表示
- artifactId = 'contextholder' // 库名称
- version = '1.1.1' // 库版本
- }
- }
-
- repositories {
- maven {
- allowInsecureProtocol = true // 仓库默认不允许使用非https协议,所以这里设置为允许
- url 'http://192.168.1.251:8081/content/repositories/android_repositories/' // 公司maven仓库地址
- credentials {
- username 'even' // maven仓库账号
- password '123456' // maven仓库密码
- }
- }
- }
- }
- }
-
按如上图的方式操作即可,第3步为选择你这个publish任务所在的模块。第4步输入publish然后按回车,这样发布的aar是带源码的,即打开类时可以看到源代码。
使用生成的aar
在settings.gradle中要先把公司的maven仓库地址设置好,如下:
- dependencyResolutionManagement {
- repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
- repositories {
- google()
- mavenCentral()
-
- // 公司仓库
- maven {
- allowInsecureProtocol = true // 仓库默认不允许使用非https协议,所以这里设置为允许
- url 'http://192.168.1.251:8081/content/repositories/android_repositories/'
- }
- }
- }
- rootProject.name = "ContextHolderLib"
- include ':app'
- include ':ContextHolder'
-
设置好仓库地址后,就可以在module的build.gradle中依赖我们的aar库了,如下:
- dependencies {
-
- implementation 'androidx.core:core-ktx:1.5.0'
- implementation 'androidx.appcompat:appcompat:1.2.0'
-
- // ContextHolder
- implementation 'cn.android666.contextholder:contextholder:1.1.1'
- }
-
实现本功能时参考的一些连接如下:
2023.1.30更新,目前版本是:Android Studio Dolphin | 2021.3.1 Patch1,在发布aar到maven是官方已有更新官方教程:https://developer.android.com/studio/publish-library,一定要看英文版,中文版的内容是过时的。
简化内容如下:
- plugins {
- id 'com.android.library'
- id 'org.jetbrains.kotlin.android'
- id 'maven-publish'
- }
-
- android {
-
- compileSdk 33
-
- namespace 'cn.dazhou.utils'
-
- defaultConfig {
- 。。。
- }
-
- 。。。
-
- publishing {
- singleVariant('release') {
- withSourcesJar()
- }
- }
- }
-
- dependencies {
- 。。。
- }
-
- // 用于把aar打包到maven仓库的任务,官方教程:https://developer.android.com/studio/publish-library,一定要看英文版,中文版的内容是过时的。
- publishing {
- publications {
- release(MavenPublication) {
- groupId = 'cn.dazhou.utils'
- artifactId = 'utils'
- version = '1.6.8'
-
- afterEvaluate {
- from components.release
- }
- }
- }
- repositories {
- maven {
- allowInsecureProtocol = true // 仓库默认不允许使用非https协议,所以这里设置为允许
- url 'http://192.168.1.251:8081/content/repositories/android_repositories/'
- credentials {
- username 'even'
- password '123456'
- }
- }
- }
- }
-