Note 6/1/2020: Android Studio 4.1 Canary 10 w/Gradle >= 6.5 has updated instructions. If you are seeing an "Unsupported BuildConfig type : java.util.Date
error, scroll down for the fix.
[Older Instructions]
In build.gradle
, each of your build types should have a buildConfigField
. (This is a simplified version of the configuration- you're likely to have other stuff in here, but I wanted to show where you put it):
android {
signingConfigs {
buildTypes {
debug {
buildConfigField "java.util.Date", "BUILD_TIME", "new java.util.Date(" + System.currentTimeMillis() + "L)"
}
release {
buildConfigField "java.util.Date", "BUILD_TIME", "new java.util.Date(" + System.currentTimeMillis() + "L)"
}
}
}
}
(Note that "BuildConfigField
" is the newer version of "BuildConfigLine
" as of the 0.8.0 build system.)
The next time gradle does assembleRelease or assembleDebug, it should generate:
./build/source/buildConfig/releaseORdebug/com/your/project/BuildConfig.java
Next, inside that BuildConfig
file, you should see something has been auto-generated like:
public final class BuildConfig {
public static final java.util.Date BUILD_TIME = new java.util.Date(1395794838381L);
}
So, to access the build date within your app....
Date buildDate = BuildConfig.BUILD_TIME;
Log.i("MyProgram", "This .apk was built on " + buildDate.toString());
(You can format the date however you like using a SimpleDateFormat.)
Update 6/1/2020 -- In Android Studio 4.1 Canary 10 w/Gradle 6.5, the above solution results in an "Unsupported BuildConfig type : java.util.Date
" error. A slight variation to the above should be used instead:
android {
signingConfigs {
buildTypes {
debug {
buildConfigField("String", "BUILD_TIME", System.currentTimeMillis().toString())
}
release {
buildConfigField("String", "BUILD_TIME", System.currentTimeMillis().toString())
}
}
}
}
Update 7/30/2020 After gradle 6.6-rc4, you need to include the enclosing quotes for the time by changing to this line:
buildConfigField("String", "BUILD_TIME", "\"" + System.currentTimeMillis().toString() + "\"")
Inside the BuildConfig
file, you should see something has now been auto-generated like:
public final class BuildConfig {
public static final String BUILD_TIME = "1590735284503";
}
So now, to access the build date within your app....
private Date buildDate = new Date(Long.parseLong(BuildConfig.BUILD_TIME));
Log.i("MyProgram", "This .apk was built on " + buildDate.toString());
As before, you can format the date however you like using a SimpleDateFormat.
Hope this is helpful.