简体   繁体   中英

How to get the JDK path in Gradle within Android Studio?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM