android - 从 Gradle 4.1 上的解析配置中获取依赖项

标签 android gradle

在以前版本的 Gradle android 插件上,我可以通过我自己的任务,使用这个获取 jar 依赖项的路径:

android.libraryVariants.all { variant ->
    task "copyDependencies${variant.name.capitalize()}"(type: Copy) {
        configurations.compile.files().each { dependency ->
            from dependency.path
        }
        into project.projectDir.path + "/build/libs/${variant.name}"
    }
}

但是在这个插件的最新版本中,compile 被弃用了,他们引入了 apiimplementation 配置,所以当我尝试使用之前的代码,gradle 表示:

Resolving configuration 'api' directly is not allowed

对引入的这个新变化有什么建议吗?


更新

我有一个依赖项列表和过滤器来进行配置:

android.libraryVariants.all { variant ->

    task "copyDependencies${variant.name.capitalize()}"(type: Copy) {
        from {
            variant.getCompileConfiguration().files().each { dependency ->
                configurations.api.getDependencies().each { configDep ->
                    if (dependency.name.contains(configDep.name)) {
                        from dependency.path
                    }
                }
            }
        }
        into project.projectDir.path + "/build/libs/${variant.name}"
    }
}

但是这个解决方案仍然存在问题,当项目 B 依赖于项目 A 时会上瘾。两者都定义了这个任务,Gradle 不会构建。

最佳答案

最后,我找到了从一个配置复制依赖的解决方案:

android.libraryVariants.all { variant ->
    task "copyDependencies${variant.name.capitalize()}"() {
        outputs.upToDateWhen { false }
        doLast {
            println "Executing from in copyDependencies${variant.name.capitalize()}"
            variant.getCompileConfiguration().getAllDependencies().each { dependency ->
                configurations.api.getDependencies().each { configDep ->
                    if (dependency.name.contains(configDep.name)) {
                        println "Dependency detected: " + dependency.name
                        variant.getCompileClasspath().each { fileDependency ->
                            if (fileDependency.absolutePath.contains(dependency.name)) {
                                println fileDependency.absolutePath
                                copy {
                                    from fileDependency.absolutePath
                                    into project.projectDir.path + "/build/intermediates/bundles/${variant.name}/libs"
                                    exclude '**/classes.jar'
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

关于android - 从 Gradle 4.1 上的解析配置中获取依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47591569/

相关文章:

android - 如何在按下后退键时关闭对话框!

java.lang.ClassNotFoundException : org. sqlite.JDBC Androidstudio Java 模块

java - Gradle 任务 assembleDebug 失败,退出代码为 1(运行时异常)

android - Gradle 同步失败 - 找不到 ID 为 'com.google.gms.google-play-services' 的插件

android - 在 gradle 中定义可从任何子模块访问的枚举

android - SoundPool 停止功能不停止

android - 在 Android 4.1 到 5.0 的 Cordova 应用程序上启用 TLS 1.2

java - 调用Action Bar导致错误

android - 拍照 "simply"不工作

android - 在根项目中找不到任务 'installRelease'