Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject Android configuration to each subproject with Gradle?

Rather than duplicating the android configuration block in each of the sub projects:

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"

    defaultConfig {
        minSdkVersion 9
        targetSdkVersion 14
    }
}

I would much rather put this in the top-level/root gradle build file like:

subprojects{
    android {
        compileSdkVersion 19
        buildToolsVersion "19.0.0"

        defaultConfig {
            minSdkVersion 9
            targetSdkVersion 14
        }
    }
}

However, this doesn't work. :(

Error: "..Could not find method android() for arguments..."

like image 303
CasualT Avatar asked Jan 09 '14 22:01

CasualT


People also ask

What is subproject in Gradle?

The subproject producer defines a task named buildInfo that generates a properties file containing build information e.g. the project version. You can then map the task provider to its output file and Gradle will automatically establish a task dependency. Example 2.

How do you add dependency from one project to another in Gradle?

To add a dependency to your project, specify a dependency configuration such as implementation in the dependencies block of your module's build.gradle file.


1 Answers

The solution to this turned out to be:

subprojects{
    afterEvaluate {
        android {
            compileSdkVersion 19
            buildToolsVersion "19.0.0"

            defaultConfig {
                minSdkVersion 9
                targetSdkVersion 14
            }
        }
    }
}

As far as I know, this is because to process/use the android{...} at evaluation time means it must be present (ie. explicitly written or included as part of an 'apply plugin') as soon as it hits the subprojects in the root build file. And, more accurately, it means that the top-level project must have it defined (which it likely doesn't because it might not be an 'android' or 'android-library' build itself). However, if we push it off to after the evaluation then it can use what is available within each subproject directly.

This question + solution also assume that all subprojects are some form of android project (in my case true, but not necessarily for others). The safer answer would be to use:

subprojects{
    afterEvaluate {
        if(it.hasProperty('android')){
            android {
                compileSdkVersion 19
                buildToolsVersion "19.0.0"

                defaultConfig {
                    minSdkVersion 9
                    targetSdkVersion 14
                }
            }
        }
    }
}
like image 133
CasualT Avatar answered Sep 18 '22 12:09

CasualT