if (project.plugins.hasPlugin('com.android.library')) {
    android.libraryVariants.all { variant ->
        Task javadocTask = task("generate${variant.name.capitalize()}Javadoc", type: Javadoc) {
            group = 'artifact'
            description "Generates Javadoc for $variant.name"

            // Source files from the variant
            source = variant.javaCompiler.source

            // Classpath from the variant + android.jar
            String androidJar = "${android.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar"
            classpath = variant.javaCompiler.classpath + files(androidJar)

            // The Android online reference doesn't include package-list, so we have to use the local one
            String packageListRef = "${android.sdkDirectory}/docs/reference/"
            options.linksOffline 'http://d.android.com/reference/', packageListRef

            // Additional links for any RxJava references
            options.links 'http://reactivex.io/RxJava/javadoc/'

            // Exclude generated files
            exclude '**/BuildConfig.java'
            exclude '**/R.java'

            // Output to a unique javadoc folder per variant
            destinationDir = new File(project.docsDir, "javadoc-$variant.name")
        }

        // For official releasese, don't prefix the name so the artifact is published correctly
        // (Can't seem to modify it for publishing, for whatever reason...)
        String classifierPrefix = (variant.name == 'release') ? '' : "$variant.name-"

        Task javadocJarTask = task("generate${variant.name.capitalize()}JavadocJar", type: Jar, dependsOn: javadocTask) {
            group = 'artifact'
            description = "Generates Javadoc jar for $variant.name"

            classifier = "${classifierPrefix}javadoc"
            from javadocTask.destinationDir
        }

        Task sourcesJarTask = task("generate${variant.name.capitalize()}SourcesJar", type: Jar) {
            group = 'artifact'
            description = "Generates sources jar for $variant.name"

            classifier = "${classifierPrefix}sources"
            from variant.javaCompiler.source
        }

        if (variant.name == 'release') {
            // There's a lot of "magic" around the archives configuration; easier
            // just to embrace it rather than try to configure around it
            artifacts {
                archives javadocJarTask, sourcesJarTask
            }
        }
        else {
            // Create a configuration we can publish from for each variant
            String configurationName = "archives${variant.name.capitalize()}"
            configurations.create(configurationName)
            artifacts.add configurationName, javadocJarTask
            artifacts.add configurationName, sourcesJarTask
        }
    }
}