0

When building an Android application with Gradle we need to point the ANDROID_HOME to our build. Maybe using an environment variable or something in the local.properties file.

I'm trying to find a way to automatically define and use this, if possible.

I've almost achieved the expected result, but because I wasn't able to change the System.env environment variables, this vetoed me.

In this Android class com.android.build.gradle.internal.SdkHandler#findSdkLocation we can see how it is finding and configuring the android sdk location.

Do we have a way to set this environment variable before the project configuration phase starts?

It looks like it needs to be before the include(":android_project") in our settings.gradle.kts.

GarouDan
  • 3,743
  • 9
  • 49
  • 75

1 Answers1

0

I've found a solution, not sure if is the best one.

Changing the System.getenv() variables, using a Kotlin adapted form of this answer:

@Suppress("UNCHECKED_CAST")
@Throws(Exception::class)
fun addAdditionalEnvironmentVariables(additionalEnvironmentVariables: Map<String, String>) {
    try {
        val processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment")
        val theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment")
        theEnvironmentField.isAccessible = true
        val env = theEnvironmentField.get(null) as MutableMap<String, String>
        env.putAll(additionalEnvironmentVariables)
        val theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment")
        theCaseInsensitiveEnvironmentField.isAccessible = true
        val cienv = theCaseInsensitiveEnvironmentField.get(null) as MutableMap<String, String>
        cienv.putAll(additionalEnvironmentVariables)
    } catch (e: NoSuchFieldException) {
        val classes = Collections::class.java.getDeclaredClasses()
        val env = System.getenv()
        for (cl in classes) {
            if ("java.util.Collections\$UnmodifiableMap" == cl.getName()) {
                val field = cl.getDeclaredField("m")
                field.setAccessible(true)
                val obj = field.get(env)
                val map = obj as MutableMap<String, String>
                map.clear()
                map.putAll(additionalEnvironmentVariables)
            }
        }
    }
}
GarouDan
  • 3,743
  • 9
  • 49
  • 75