The answer that loads local.properties manually above obviously works, and the next one that requires you to know which plugin was applied should work as well.
These approaches might be a little better for some since they are more generic because they work regardless of whether you're using the Application, Test, or Library plugin. These snippets also give you full programmatic access to all of the Android plugin config (Product Flavors, Build Tools version, and much more):
If you need access in a build.gradle file that is using the Android Gradle Plugin simply access the Android DSL directly as it's now available directly:
project.android.sdkDirectory
The longer form (below) of this is handy if you're creating custom Gradle Tasks classes or Plugins or simply want to view which properties are available.
// def is preferred to prevent having to add a build dependency.
def androidPluginExtension = project.getExtensions().getByName("android");
// List available properties.
androidPluginExtension.properties.each { Object key, Object value ->
logger.info("Extension prop: ${key} ${value}")
}
String sdkDir = androidPluginExtension.getProperties().get("sdkDirectory");
System.out.println("Using sdk dir: ${sdkDir}");
At the time of this posting there is also a handy adbExe
property that is definitely worth noting.
This code has to execute AFTER the Android Gradle Plugin is configured per the Gradle livecycle. Typically this means you put it in the execute
method of a Task
or place it AFTER the android
DSL declaration in an Android app/libraries' build.gradle
file).
These snippets also come with the caveat that as you upgrade Android Gradle Plugin versions these properties can change as the plugin is developed so simply test when moving between versions of the Gradle and Android Gradle plugin as well as Android Studio (sometimes a new version of Android Studio requires a new version of the Android Gradle Plugin).