Use Gradle like a boss

 

Gradle is awesome build tool, and I’m so happy that Android Studio uses it (who ever programmed in Eclipse knows what I’m talking about). I would like to share some tips and tricks.

Update multiple libs version at once

This is really useful with Google’s Android support library, but you will find other examples as well. First, you will need to create extra property, in my example, I name it androidSupportVersion. After that, use this property with your dependencies put a $ sign at the beginning and surround it with curly brackets.

The cool thing about this is that Android Studio will still tell you when a newer version is available.

BuildConfig

This class is automatically generated, and here (with Gradle) you can store some global variables, for example, probably the most common use of this is to have two different API endpoints.

Resources

Similar to previous part, we can use Gradle for generating resources, for example, different name of the app.

You can use all resource types as the type for resValue: array, attr, bool, color, declare-styleable, dimen, fraction, id, integer, plurals, string, style.

Manifest placeholders

We can also define something useful and use it in our app manifest.

defaultConfig {
    ...
    manifestPlaceholders = [mapKey: "b279b6400b0bf87fba17c98249a66df0"]
}

And now we can use it in manifest like this:

<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="${mapKey}" />

Signing configs

We can store keystore private info under gradle.properties

keystore=/home/myname/keystore/mykey
keystore_password=mypass
key_alias=mykey
key_password=keypass

and it to the gradle file:

signingConfigs {
 release {
 storeFile file("${keystore}")
 storePassword "${keystore_password}" 
 keyAlias "${key_alias}" 
 keyPassword "${key_password}"
 }
}
buildTypes {
 release {
 signingConfig signingConfigs.release
 ..
 }
}

Do you need SHA-1 certificate fingerprint? You could use a keytool, but there is a lot simpler solution. Just run gradle:

 ./gradlew signingReport

Git in Gradle

You can use Git SHA or build time inside your Gradle, for example, you can add Git SHA to your versionNameSuffix just for debug build type.

def gitSha = 'git rev-parse --short HEAD'.execute([], project.rootDir).text.trim()
def buildTime = new Date().format("yyyy-MM-dd'T'HH:mm:ss'Z'", TimeZone.getTimeZone("UTC"))

Conclusion

Gradle is an awesome tool for our apps, and I know that there is a lot more. Did I miss something important? Tell me in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *