0

I want my Android application to know at runtime when the application was built. I am new to Gradle, but it seems very flexible and I think it might be possible to achieve this without any external helper programs or token replacement.

My idea was to compute a timestamp string in some sort of a Gradle pre-build task. Then I would like to pass this string as a system property to the Java application. For example:

def timestamp = ...
systemProperty 'my.build.timestamp' timestamp

And then retrieve the timestamp at runtime in Java:

String iWasBuiltAt = System.getProperty("my.build.timestamp");

How would I go about writing the neccesary Gradle code to achieve this? More specifically, where/how do invoke my custom task and is it possible to add system properties in such a way as described above.

pqvst
  • 4,344
  • 6
  • 33
  • 42
  • are you using this for version number? – Ethan Oct 11 '13 at 14:55
  • possible duplicate of [How to programmatically read the date when my Android apk was built?](http://stackoverflow.com/questions/3540739/how-to-programmatically-read-the-date-when-my-android-apk-was-built) – sschuberth Sep 03 '14 at 09:29

1 Answers1

4

The following will add a buildTime constant to your BuildConfig class (this class is auto-generated by the build system).

defaultConfig {
    buildConfig  "public final static String buildTime = \"" + new Date() + "\";"
}

In any Android Java file, you can use it like so (The build config is in the default package of your app which you will have to import):

Log.v("foo", "buildtime:" + BuildConfig.buildTime);

You can use groovy date formatting functions to format the date differently. You could also change this to store the epoch milliseconds and then parse it in Java.

defaultConfig means that this will be added builds of every buildType.

Read more about build types, the defaultConfig etc. here : http://tools.android.com/tech-docs/new-build-system/user-guide

Not sure why you would want to know this in the app. I think using the revision number or hash of your version control system might make more sense than the date.

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
treesAreEverywhere
  • 3,722
  • 4
  • 28
  • 51
  • 2
    Great! I use the build time to determine the expiration date of an internal "evaluation" flavor of my app. – pqvst Oct 13 '13 at 11:12
  • 3
    `buildConfigField "long", "BUILD_TIME_MILLIS", "${System.currentTimeMillis()}L"` – Mark Jul 22 '15 at 08:28