首页 > 解决方案 > 在构建 Android 应用程序之前,将 jar 从其他目录拉到 libs 文件夹

问题描述

我有一个 Android 项目,它依赖于外部 jar 文件,即A.jar.

我已将我的 android 配置build.gradle为首先构建构建的项目A.jar。然后 Android 构建继续进行。

jar 构建后,将 jar 从其构建文件夹复制到 android 项目 lib 文件夹的最佳方法是什么?

所以构建应该继续......

构建 Jar > 将 Jar 复制到 Libs > 构建 Android 项目。

我不使用 Android Studio,所以我只通过 gradle 配置文件操作来配置我的项目。

当前构建 jar 的项目已列为依赖项app/build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "saf.mobilebeats2"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        debug {
            applicationIdSuffix ".debug"
            debuggable true
        }
    }
}

dependencies {
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    implementation 'com.android.support:appcompat-v7:26.0.0'
    implementation project(':dawcore')
    // runtime files('../DawCore/build/libs/DawCore.jar')
}

标签: javaandroidgradleandroid-gradle-plugin

解决方案


由于您没有使用 Android Studio 并且依赖模块位于其他一些项目正在使用它的其他地方,您可能会考虑在libs依赖模块完成构建并创建 jar 后将 jar 复制到您的目录中复制。所以整体执行如下:

  • 任务1.构建依赖模块
  • 任务 2. 将 jar 文件复制到您的 android 应用程序要使用的特定位置。
  • 任务 3. 在构建您的 Android 应用程序时,将 jar 文件从该特定位置复制到您的libs目录。
  • 任务 4. 使用构建 jarcompile files('libs/jar-from-dependency.jar')

build.gradle现在对于任务 1 和 2:在依赖模块的文件中添加以下内容。因此,在构建依赖模块之后,这会将 jar 复制到复制任务中指定的位置。检查下面的复制功能,了解如何在 gradle 中编写复制功能。

apply plugin: 'java'

task finalize << {
    println('Here use the copyTask to copy the jar to a specific directory after each build of your library module')
}

build.finalizedBy(finalize)
// compileJava.finalizedBy(copyJarToAndroid) <-- In your case

这是与此相关的必要功能的文档。

对于任务 3:现在任务很简单。在使用 gradle 构建之前,您需要将 jar 从该特定位置复制到您的 Android 应用程序项目中。以下是在构建项目之前如何启动复制任务的方法。

task copyFiles(type: Copy) {
    description = 'Copying the jar'
    from 'your/jar/directory'
    into project(':Path:To:ModuleFrom:Settings.gradle').file('./libs')
    include 'jar-from-dependency.jar'
}

project.afterEvaluate {
    preBuild.dependsOn copyFiles
}

clean.dependsOn copyFiles
clean.mustRunAfter copyFiles

这将在copyFiles启动 gradle clean 时运行任务。

dependencies因此对于任务 4:在您的部分中添加 jar 。

dependencies {
    // ... Other dependencies
    compile files('libs/jar-from-dependency.jar')
}

推荐阅读