android - 如何让 android gradle 项目更喜欢库依赖​​ AAR 而不是 JAR?

标签 android gradle

我有一个 android 库项目(称为 my-lib),它在 build.gradle 文件中使用此技巧生成 AAR 和 JAR:

android.libraryVariants.all { variant ->
  def name = variant.buildType.name
  def task = project.tasks.create "jar${name.capitalize()}", Jar
  task.dependsOn variant.javaCompile
  task.from variant.javaCompile.destinationDir
  artifacts.add('archives', task);
}

本库工程不包含任何Android资源,生成一个JAR包方便其他一些没有使用maven和gradle的系统使用。在 gradle 文件中声明它们依赖于此 android 库的 Android 应用程序,就像在它们的 gradle 文件中一样:

dependencies {
  compile 'com.mycompany:my-lib:VERSION'
}

但是这些 android 应用程序正在获取 JAR 文件而不是 AAR,因此错过了 AAR 中的 proguard.txt 文件,该文件是使用库 gradle 中的声明放置在那里的文件:

android {
  buildTypes.all {
    consumerProguardFiles 'proguard-rules.pro'
  }
}

android gradle 插件生成的 pom 文件缺少 packaging 条目,它看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany</groupId>
  <artifactId>my-lib</artifactId>
  <version>VERSION</version>
</project>

packaging 条目应该指定 aar 以便其他项目获得 AAR 而不是 JAR,但我该怎么做呢?也许有一种方法可以生成具有不同名称的 JAR,这样它就不会与 AAR 冲突?

更新:

我无法在所有依赖项中指定 @aar,因为一些依赖项是使用 implementation project(':my-lib') 指定项目的库并且 gradle 不接受 @aar 。然后,当我尝试将依赖项添加到应用程序时,出现此错误:D8: Program type already present with the name of a class that is in my-lib.我确保我所有的依赖项都通过 implementation 而不是 compile 引用 my-lib 并且我看到在依赖库的中间 POM 文件中引用看起来像这样:

<dependency>
 <groupId>mycompany</groupId>
  <artifactId>my-lib</artifactId>
  <version>1</version>
  <scope>runtime</scope>
</dependency>

因此运行时范围似乎是正确的。

我正在使用 https://github.com/dcendents/android-maven-gradle-plugin/用于将库发布到我的本地 Maven 缓存的插件,因此不同 git repos 中的许多其他 Android 应用程序可以访问 android 库。这出现在我的库 build.gradle 文件的顶部:

apply plugin: 'com.android.library'
apply plugin: 'android-maven'

group = 'com.mycompany'
version = '1'

repositories {
    mavenLocal()
}

最佳答案

由于 Gradle Android Maven 插件是标准 Maven 插件的修改版,根据 documentation ,你可以试试这个:

uploadArchives {
    repositories {
        mavenDeployer {
            pom.packaging = 'aar'
        }
    }
}

关于android - 如何让 android gradle 项目更喜欢库依赖​​ AAR 而不是 JAR?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49868039/

相关文章:

java - 尝试在Java中导入vk.core.api

Android Studio 打开不正确的 java 类文件。错误 : "Failed linking the resources."

groovy - 在Gradle构建中使用Groovy类

java - Android X 中的透明导航栏

android - 有没有办法在双卡手机的两个插槽中获取运营商名称?

java - 为较低的 sdk/jdk 重建项目。失败 [INSTALL_FAILED_OLDER_SDK]

java - Google 应用引擎的 gradle 单元测试在哪里期望 persistence.xml?

maven - 如何在工作区中使用同一项目根目录的多个存储库?

android - 找不到处理 https ://Intent 的 Activity

第一个 Activity 的android全屏