In order to build some Android projects, it's necessary to set the environment variable JAVA_HOME
. (See this Stack Exchange question and flutter bug report.)
This is the case for a project I'm working on. I would like to change the Gradle file so it is not necessary to set JAVA_HOME
.
Is there any way for Gradle to get the path to the JDK used by the enclosing Android Studio process (or for the process to pass in the JDK without user intervention)? This should work when JAVA_HOME
had not been set.
By default, Gradle uses the java version from the JAVA_HOME environment variable path configured in the machine, and JAVA_HOME points to JDK installed on the machine. For example, the machine is installed with the JDK 1.8 version and the Gradle project needs a java 11 version.
Gradle uses whichever JDK it finds in your path (to check, use java -version). Alternatively, you can set the JAVA_HOME environment variable to point to the install directory of the desired JDK.
Since Android apps are written in Java, you will need the Oracle Java compiler and libraries on your system. These are collectively called the Java Development Kit or "JDK" for short.
you can define a task in your_project_path/app/build.gradle
task javaHome {
println "JAVA_HOME:" + System.getProperty("java.home")
}
run task:
./gradlew -q app:javaHome
RESULT:
JAVA_HOME:/usr/lib/jvm/java-8-openjdk-amd64/jre
There are generally two options available:
a) Edit the gradle.properties
file and define which JDK you want to use:
org.gradle.java.home=(path to JDK home)
There it cannot be set dynamically, because it's an egg/hen problem.
And it might also fail on other computers, because the path may vary.
But one can pass it as command-line option:
./gradlew -Dorg.gradle.java.home=$JAVA_PATH
For reference: Build Environment.
b) However, one can also add an export JDK_HOME
statement on top of file gradlew
. Came up with a shell script, which can at least detect the default JDK install on Linux (Android Studio runs on JRE):
tmp=`which java`
export JAVA_HOME=${tmp::-9}
echo $JAVA_HOME
/usr/java/jdk1.8.0_172
Of course, one also would have to consider no JDK being present at all:
/usr/bin/which: no java in ...
Generally, this assumes a default JDK had been set with alternatives, as a package manger usually would do; eg yum install jdk1.8.0_102.x86_64
. The problem here is, that there is no easy way to identify which JDK path to use on Windows, because Windows has no which
command and one would likely have to read from the registry. A helper PS script or executable could look up the value and truncate as required, called from file gradlew.bat
. There still may be other ways to get the path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With