Include jar file with Java sources in Android aar

别等时光非礼了梦想. 提交于 2020-05-27 06:46:27

问题


I have a gradle task to create a jar file containing Java source files to be included in an Android aar library package. These files will serve as Javadoc for JNI to a C++ library also bundled in the aar package.

I cannot possibly figure out how to include the jar file and not compile the files within. it seems that the Java files in the jar file are compiled, which does not help me - I just want to include them so that they are available to developers using that aar package.

The created jar file has all the sources and is in the output aar inside its libs directory, but it has no contents.

How can I add the Java sources to my aar?

Jar creation

The Jar is created as follows and ends up in the build/libs folder of my module.

task generateMySources(type: Jar) {
    classifier = 'sources'
    from android.sourceSets.main.java.srcDirs
}

artifacts {
    archives generateMySources
}

preBuild.dependsOn(":myModule:generateMySources")

dependencies {
    // The jar is included but it is empty inside the aar.
    compile files('build/libs/myModule-sources.jar')
}

The output jar contains:

.
├── com
│   └── my
│       └── app
│           └── jni
│               ├── File1.java
│               ├── File2.java
│               ├── File3.java
│               └── File4.java
└── META-INF
    └── MANIFEST.MF // Contains "Manifest-Version: 1.0" only.

The jar exists inside the aar inside the libs directory, but now it is empty.


回答1:


Only thing I could come up with is to add your sources to the .aar file after it's built like so

task generateMySources(type: Jar) {
    classifier = 'sources'
    from android.sourceSets.main.java.srcDirs
}
task addMySourcesToAar(type: Jar) {
    archiveName "myModuleWithSources.aar"
    destinationDir file("build")
    from zipTree("build/outputs/aar/myModule-release.aar")
    from fileTree("build").include("libs/myModule-sources.jar")
}
afterEvaluate { project ->
    project.tasks.preBuild.dependsOn generateMySources
    project.addMySourcesToAar.dependsOn build
}
artifacts {
    archives addMySourcesToAar.archivePath
}

and run

./gradlew myModule:addMySourcesToAar

I didn't add anything to dependencies like you did




回答2:


For thus who are using Gradle Kotlin DSL:

tasks.register<Jar>(name = "sourceJar") {
    from(android.sourceSets["main"].java.srcDirs)
    classifier = "sources"
}

publishing {
    publications {
        create<MavenPublication>(name = "Maven") {
            run {
                groupId = "groupId"
                artifactId = "module-name"
                version = "1.0"
                artifact("$buildDir/outputs/aar/module-name-release.aar")
                artifact(tasks["sourceJar"])
            }
        }
    }
}


来源:https://stackoverflow.com/questions/41569974/include-jar-file-with-java-sources-in-android-aar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!