Android如何构建自己的库在build.gradle中引用-教程+跳坑

本文详细介绍了如何创建Android库项目,将其提交至GitHub,并通过JitPack进行发布,以便在其他项目中引用。包括创建module、构建release版本、在JitPack上获取依赖路径等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开发Android也有一定的年头的,承蒙大神们通过不懈的努力带给我们众多的便利!或许也到自己贡献的时候了,那么我们先学习一下如何构建自己的库,并且在gradle中的引用!

步骤

前期准备:

新建一个project,提交到github上面去

 

 

创建lib的module

这个module里的代码就是别人可以引用的代码

创建你分享的代码,例如下图

在github上创建release版本

把所有的代码提交到github上面后,如下图所示在github上创建release版本

jitpack上获取路径

生成release包之后开始,打开https://jitpack.io,登录自己的github账号,把仓库的地址复制进去即可,如果log图标和status的按钮都是原谅色,那么恭喜你,成功了。点击get it,下面有引入教程

 

引用自己的库

 

跳坑

project目录下的build.gradle设置

//低版本的gradle使用的plugin也相应会低一点
classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'

 

module目录下的build.gradle设置

apply plugin: 'com.github.dcendents.android-maven'
group='com.github.KubyWong'//com.github.{你的的账号名}

 

https://jitpack.io红色log如何处理

如上图,正确的情况下log是绿色的,搞这个的时候感觉有点背,无论怎么提交都是出错的,在项目中当然也无法正常引入。当出现下面这个问题的时候,别想了,重新来一次创建流程。(起一个project,放到github上,创建release版本,jitpack中获取状态信息)

Build starting...
Start: Thu Jun 27 14:34:38 UTC 2019 861df077f5ba
Git:
1.2.3-0-gd0f9aee
commit d0f9aeec13db0bbe6abd4aafeffc6bda18f423a7
Author: KubyHuang 
Date:   Thu Jun 27 22:29:49 2019 +0800

    使用1.5的插件地址
    com.github.dcendents:android-maven-gradle-plugin:1.5

Found Android manifest
Android SDK version: 28. Build tools: 29.0.0
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8 -Dhttps.protocols=TLSv1.2
Warning: File /opt/android-sdk-linux/.android/repositories.cfg could not be loaded.

Installing Android platform 28
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8 -Dhttps.protocols=TLSv1.2
Warning: File /opt/android-sdk-linux/.android/repositories.cfg could not be loaded.
Installing Build-tools 29.0.0 
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8 -Dhttps.protocols=TLSv1.2
Warning: File /opt/android-sdk-linux/.android/repositories.cfg could not be loaded.
Found gradle
Gradle build script
Using gradle wrapper
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8 -Dhttps.protocols=TLSv1.2
Downloading https://services.gradle.org/distributions/gradle-5.1.1-all.zip
.
Unzipping /home/jitpack/.gradle/wrapper/dists/gradle-5.1.1-all/97z1ksx6lirer3kbvdnh7jtjg/gradle-5.1.1-all.zip to /home/jitpack/.gradle/wrapper/dists/gradle-5.1.1-all/97z1ksx6lirer3kbvdnh7jtjg
Set executable permissions for: /home/jitpack/.gradle/wrapper/dists/gradle-5.1.1-all/97z1ksx6lirer3kbvdnh7jtjg/gradle-5.1.1/bin/gradle

Welcome to Gradle 5.1.1!

Here are the highlights of this release:
- Control which dependencies can be retrieved from which repositories
- Production-ready configuration avoidance APIs

For more details see https://docs.gradle.org/5.1.1/release-notes.html

------------------------------------------------------------
Gradle 5.1.1
------------------------------------------------------------

Build time:   2019-01-10 23:05:02 UTC
Revision:     3c9abb645fb83932c44e8610642393ad62116807

Kotlin DSL:   1.1.1
Kotlin:       1.3.11
Groovy:       2.5.4
Ant:          Apache Ant(TM) version 1.9.13 compiled on July 10 2018
JVM:          1.8.0_191 (Oracle Corporation 25.191-b12)
OS:           Linux 4.14.63-xxxx-std-ipv6-64 amd64

Getting tasks: ./gradlew tasks --all
0m4.655s
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8 -Dhttps.protocols=TLSv1.2
Tasks: 

WARNING:
Gradle 'install' task not found. Please add the 'maven' or 'android-maven' plugin.
See the documentation and examples: https://jitpack.io/docs/

Adding maven plugin
Found android library build file in app
Running: ./gradlew clean -Pgroup=com.github.KubyWong -Pversion=1.2.3 install
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8 -Dhttps.protocols=TLSv1.2

> Configure project :
Gradle version Gradle 5.1.1

FAILURE: Build failed with an exception.

* What went wrong:
Task 'install' not found in root project 'build'.

* Try:
Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
Build tool exit code: 0
Looking for artifacts...
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8 -Dhttps.protocols=TLSv1.2
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8 -Dhttps.protocols=TLSv1.2
Looking for pom.xml in build directory and ~/.m2
2019-06-27T14:35:20.897507593Z
Exit code: 0

ERROR: No build artifacts found

 

<think>我们正在处理一个关于将Android项目中的build.gradle.kts文件(使用KotlinDSL)转换为传统的build.gradle文件(使用GroovyDSL)的问题。根据提供的引用,我们知道build.gradle.kts是使用Kotlin编写的构建脚本,而build.gradle是使用Groovy编写的。转换时需要注意两种语言的语法差异。步骤:1.文件扩展名:将`.kts`改为`.gradle`(例如,`build.gradle.kts`->`build.gradle`)。2.语法转换:因为Kotlin和Groovy的语法不同,所以需要将Kotlin语法改写为Groovy语法。常见的转换点:-变量定义:Kotlin中使用`val`,Groovy中可以使用`def`或直接赋值(无类型声明)。-函数调用:Kotlin中调用函数使用括号,Groovy中通常可以省略括号(但有时需要保留)。-属性赋值:在Kotlin中,我们使用`=`进行赋值,在Groovy中同样使用`=`,但要注意在闭包中的赋值方式。-闭包:Groovy中大量使用闭包(用花括号`{}`表示),而KotlinDSL中使用的是lambda表达式,但语法相似,不过细节有差异。-导入:Groovy不需要像Kotlin那样显式导入某些类(例如,文件操作相关的类),但有时也需要导入。以引用[2]中的代码为例,展示如何转换:原始KotlinDSL(build.gradle.kts)代码片段:```importjava.util.Propertiesimportjava.io.FileInputStreamvalkeystoreProperties=Properties()valkeystorePropertiesFile=rootProject.file("key.properties")if(keystorePropertiesFile.exists()){keystoreProperties.load(FileInputStream(keystorePropertiesFile))}android{signingConfigs{create("release"){keyAlias=keystoreProperties["keyAlias"]asStringkeyPassword=keystoreProperties["keyPassword"]asStringstoreFile=keystoreProperties["storeFile"]?.let{file(it)}storePassword=keystoreProperties["storePassword"]asString}}buildTypes{release{signingConfig=signingConfigs.getByName("release")}}}```转换为GroovyDSL(build.gradle)的代码:```importjava.util.Propertiesimportjava.io.FileInputStreamdefkeystoreProperties=newProperties()defkeystorePropertiesFile=rootProject.file('key.properties')if(keystorePropertiesFile.exists()){keystoreProperties.load(newFileInputStream(keystorePropertiesFile))}android{signingConfigs{release{keyAliaskeystoreProperties['keyAlias']keyPasswordkeystoreProperties['keyPassword']storeFilefile(keystoreProperties['storeFile'])storePasswordkeystoreProperties['storePassword']}}buildTypes{release{signingConfigsigningConfigs.release}}}```转换说明:-变量定义:`val`改为`def`(或者直接去掉,但在Groovy中通常使用`def`来定义变量)。-对象创建:Kotlin中`Properties()`,Groovy中`newProperties()`。-字符串:Kotlin中双引号,Groovy中单引号或双引号都可以,通常使用单引号表示普通字符串。-方法调用:Groovy中方法调用可以省略括号,例如`file(keystoreProperties['storeFile'])`也可以写成`filekeystoreProperties['storeFile']`,但为了清晰,我们保留了括号。-类型转换:Kotlin中的`asString`在Groovy中不需要,因为Groovy是动态类型。-安全调用:Kotlin中的`?.let`在Groovy中可以用`if`条件或安全导航操作符`?.`,但这里直接使用`file(keystoreProperties['storeFile'])`,因为如果`keystoreProperties['storeFile']`为null,file方法会错,所以需要确保存在。-创建签名配置:Kotlin中使用`create("release")`,Groovy中直接使用`release`(作为闭包的名字)。-获取签名配置:Kotlin中使用`signingConfigs.getByName("release")`,Groovy中可以使用`signingConfigs.release`。另外,注意Groovy中闭包的嵌套结构,以及赋值方式(在闭包内,我们使用`keyAliasvalue`而不是`keyAlias=value`,因为GroovyDSL中通常使用这种风格)。其他常见转换:-依赖声明:Kotlin:`implementation("com.android.support:appcompat-v7:28.0.0")`Groovy:`implementation'com.android.support:appcompat-v7:28.0.0'`-任务定义:Kotlin:```tasks.register("myTask"){doLast{println("Taskrunning")}}```Groovy:```taskmyTask{doLast{println'Taskrunning'}}```由于整个项目可能有多个build.gradle.kts文件(项目根目录和模块目录),需要逐一转换。建议:1.备份项目。2.逐个文件进行转换,并测试构建是否成功。3.注意Groovy和Kotlin在处理空值、集合、字符串等方面的差异。注意:转换后可能需要调整一些细节,因为两种DSL并非完全一一对应。相关问题:1.在转换过程中常见的错误有哪些?2.如何确保转换后的build.gradle文件与原来的build.gradle.kts功能一致?3.除了手动转换,有没有自动转换工具?</think>### 将 `build.gradle.kts` 转换为 `build.gradle` 的步骤 以下是完整的转换指南,包含语法差异和实际示例: #### **1. 文件扩展名修改** - 将所有 `.kts` 文件重命名为 `.gradle`: ```bash # 根目录构建脚本 mv build.gradle.kts build.gradle # 模块级构建脚本 mv app/build.gradle.kts app/build.gradle ``` #### **2. 核心语法转换** | **Kotlin DSL (`build.gradle.kts`)** | **Groovy DSL (`build.gradle`)** | |------------------------------------|--------------------------------| | `val prop = "value"` | `def prop = "value"` | | `implementation("dep:1.0")` | `implementation 'dep:1.0'` | | `file("path")` | `file('path')` | | `= assignment` (显式赋值) | 空格赋值 (如 `keyAlias alias`) | | `?.let { ... }` (空安全) | 直接调用 (需自行处理空值) | #### **3. 签名配置转换示例** **原始 Kotlin DSL ([^2] 示例):** ```kotlin // build.gradle.kts import java.util.Properties import java.io.FileInputStream val keystoreProperties = Properties() val keystorePropertiesFile = rootProject.file("key.properties") if (keystorePropertiesFile.exists()) { keystoreProperties.load(FileInputStream(keystorePropertiesFile)) } android { signingConfigs { create("release") { keyAlias = keystoreProperties["keyAlias"] as String keyPassword = keystoreProperties["keyPassword"] as String storeFile = keystoreProperties["storeFile"]?.let { file(it) } storePassword = keystoreProperties["storePassword"] as String } } buildTypes { release { signingConfig = signingConfigs.getByName("release") } } } ``` **转换后的 Groovy DSL:** ```groovy // build.gradle import java.util.Properties import java.io.FileInputStream def keystoreProperties = new Properties() def keystorePropertiesFile = rootProject.file('key.properties') if (keystorePropertiesFile.exists()) { keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) } android { signingConfigs { release { keyAlias keystoreProperties['keyAlias'] keyPassword keystoreProperties['keyPassword'] storeFile file(keystoreProperties['storeFile']) storePassword keystoreProperties['storePassword'] } } buildTypes { release { signingConfig signingConfigs.release } } } ``` #### **4. 依赖项声明转换** ```diff - // Kotlin DSL - dependencies { - implementation("androidx.core:core-ktx:1.9.0") - testImplementation("junit:junit:4.13.2") - } + // Groovy DSL + dependencies { + implementation 'androidx.core:core-ktx:1.9.0' + testImplementation 'junit:junit:4.13.2' + } ``` #### **5. 常见问题处理** - **空值问题**:移除 Kotlin 的 `?.let`,确保属性文件存在 - **类型转换**:删除 `as String`,Groovy 自动处理类型 - **函数调用**:`signingConfigs.getByName("release")` → `signingConfigs.release` - **赋值符号**:`=` 改为空格(如 `minSdk 24` 代替 `minSdk = 24`) #### **6. 验证转换** 1. 运行同步命令: ```bash ./gradlew clean assembleDebug ``` 2. 检查构建日志中的语法错误 3. 重点验证签名配置、依赖项和插件应用 > **关键提示**:转换后需彻底测试构建流程,尤其是签名和变体配置,因为两种 DSL 在闭包作用域和延迟初始化上有差异[^1][^2]。 ###
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值