Gradle is the new build system for android apps. In the build script you need to specify what SDK and build tools versions to use, and if a new developer or customer doesn’t have that exact version installed, when importing into Android Studio, they’ll hit an error message like failed to find target android-18. Or that’s the case when a bunch of developers have different versions installed. You probably don’t want to make changes in the build.gradle file all the time. So I wrote a couple of functions on Groovy to automagically select the latest versions available.
// http://www.egeek.me/importorg.codehaus.groovy.runtime.StackTraceUtilsint[]sdksAvailable(){defsdks=newByteArrayOutputStream()exec{commandLine'android','list'standardOutput=sdks}sdks=sdks// get the output.toString()// split to strings.split('\n')// leave only strings with API levels.findAll{it==~/\s*API level:.*/}// extract the API levels.collect{(it=~/\s*API level:\s*(\d+).*/)[0][1].toInteger()}// sort from highest to lowest.sort({a,b->b<=>a})sdks}inthighestSdkAvailable(intdefaultSdk){try{defsdks=sdksAvailable()defhighestSdk=sdks[0]if(highestSdk!=null){println"Using highest found SDK "+highestSdkhighestSdk}else{println"No installed SDKs found. Using default SDK "+defaultSdkdefaultSdk}}catch(any){println"Exception while determining highest SDK. Using default SDK "+defaultSdkStackTraceUtils.sanitize(any).printStackTrace()defaultSdk}}StringandroidSDKDir(){defandroidExecPath=newByteArrayOutputStream()exec{commandLine'which','android'standardOutput=androidExecPath}file(androidExecPath.toString().trim()).getParentFile().getParentFile()}String[]buildToolsAvailable(){defbuildToolsDir=newFile(androidSDKDir(),"build-tools")buildToolsDir.list().sort{a,b->b<=>a}}StringlatestBuildToolsAvailable(StringdefaultBuildTools){try{defbuildToolsVersions=buildToolsAvailable()deflatestBuildTools=buildToolsVersions[0]if(latestBuildTools!=null){println"Using latest found build tools "+latestBuildToolslatestBuildTools}else{println"No installed build tools found. Using default build tools "+defaultBuildToolsdefaultBuildTools}}catch(any){println"Exception while determining latest build tools. Using default build tools "+defaultBuildToolsStackTraceUtils.sanitize(any).printStackTrace()defaultBuildTools}}ext.compileSdkVersion=highestSdkAvailable(19)ext.buildToolsVersion=latestBuildToolsAvailable("19.0.0")
The script relies on some assumptions that are true for now. E.g., the relative path from the android executable to where different build tools are installed: ../../build-tools/. I couldn’t find a better way to get a list of available tools.