How to write build time stamp into apk
AndroidBuildMakefileAndroid Problem Overview
- Making some changes in Android Contacts package
- Using
mm
(make) command to build this application
Because I have to change and build this app again and again, so I want to add a build time stamp in the Contacts.apk
to check the build time when we runn it in the handset.
As we know, when we run mm
command, the Android.mk
(makefile) in Contacts package will be called.
And now, we can get the build time using date
-macro.
But how we can write this build time stamp into a file that our application can read at runtime?
Any suggestions?
Android Solutions
Solution 1 - Android
If you use Gradle, you can add buildConfigField
with timestamp updated at build time.
android {
defaultConfig {
buildConfigField "long", "TIMESTAMP", System.currentTimeMillis() + "L"
}
}
Then read it at runtime.
Date buildDate = new Date(BuildConfig.TIMESTAMP);
Solution 2 - Android
Method which checks date of last modification of classes.dex, this means last time when your app's code was built:
try{
ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), 0);
ZipFile zf = new ZipFile(ai.sourceDir);
ZipEntry ze = zf.getEntry("classes.dex");
long time = ze.getTime();
String s = SimpleDateFormat.getInstance().format(new java.util.Date(time));
zf.close();
}catch(Exception e){
}
Tested, and works fine, even if app is installed on SD card.
Solution 3 - Android
Since API version 9 there's:
PackageInfo.lastUpdateTime
The time at which the app was last updated.
try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
//TODO use packageInfo.lastUpdateTime
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
On lower API versions you must make build time yourself. For example putting a file into assets folder containing the date. Or using __ DATE__ macro in native code. Or checking date when your classes.dex was built (date of file in your APK).
Solution 4 - Android
Edit: My answer does not work anymore since option keepTimestampsInApk was removed. Working in 2020 is https://stackoverflow.com/a/26372474/6937282 (also https://stackoverflow.com/a/22649533/6937282 for more details)
Original answer:
A hint for solution "last modification time of classes.dex file" an newer AndroidStudio versions: In default config the timestamp is not written anymore to files in apk file. Timestamp is always "Nov 30 1979".
You can change this behavior by adding this line to file
%userdir%/.gradle/gradle.properties (create if not existing)
android.keepTimestampsInApk = true
See Issue 220039
(Must be in userdir, gradle.properties in project build dir seems not to work)
Solution 5 - Android
Install time : packageInfo.lastUpdateTime
build time : zf.getEntry("classes.dex").getTime()
Both are differnet time. You can check with the code below.
public class BuildInfoActivity extends Activity {
private static final String TAG = BuildInfoActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
PackageManager pm = getPackageManager();
PackageInfo packageInfo = null;
try {
packageInfo = pm.getPackageInfo(getPackageName(), 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
// install datetime
String appInstallDate = DateUtils.getDate(
"yyyy/MM/dd hh:mm:ss.SSS", packageInfo.lastUpdateTime);
// build datetime
String appBuildDate = DateUtils.getDate("yyyy/MM/dd hh:mm:ss.SSS",
DateUtils.getBuildDate(this));
Log.i(TAG, "appBuildDate = " + appBuildDate);
Log.i(TAG, "appInstallDate = " + appInstallDate);
} catch (Exception e) {
}
}
static class DateUtils {
public static String getDate(String dateFormat) {
Calendar calendar = Calendar.getInstance();
return new SimpleDateFormat(dateFormat, Locale.getDefault())
.format(calendar.getTime());
}
public static String getDate(String dateFormat, long currenttimemillis) {
return new SimpleDateFormat(dateFormat, Locale.getDefault())
.format(currenttimemillis);
}
public static long getBuildDate(Context context) {
try {
ApplicationInfo ai = context.getPackageManager()
.getApplicationInfo(context.getPackageName(), 0);
ZipFile zf = new ZipFile(ai.sourceDir);
ZipEntry ze = zf.getEntry("classes.dex");
long time = ze.getTime();
return time;
} catch (Exception e) {
}
return 0l;
}
}
}
Solution 6 - Android
in your build.gradle:
android {
defaultConfig {
buildConfigField 'String', 'BUILD_TIME', 'new java.text.SimpleDateFormat("MM.dd.yy HH:mm", java.util.Locale.getDefault()).format(new java.util.Date(' + System.currentTimeMillis() +'L))'
}
}
Solution 7 - Android
I use the same strategy as Pointer Null except I prefer the MANIFEST.MF file. This one is regenerated even if a layout is modified (which is not the case for classes.dex). I also force the date to be formated in GMT to avoid confusion between terminal and server TZs (if a comparison has to be made, ex: check latest version).
It result in the following code:
try{
ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), 0);
ZipFile zf = new ZipFile(ai.sourceDir);
ZipEntry ze = zf.getEntry("META-INF/MANIFEST.MF");
long time = ze.getTime();
SimpleDateFormat formatter = (SimpleDateFormat) SimpleDateFormat.getInstance();
formatter.setTimeZone(TimeZone.getTimeZone("gmt"));
String s = formatter.format(new java.util.Date(time));
zf.close();
}catch(Exception e){
}
Solution 8 - Android
So Android Developer - Android Studio User Guide - Gradle Tips and Recipes - Simplify App Development actually documents what to add in order to have a release timestamp available to your app:
android {
...
buildTypes {
release {
// These values are defined only for the release build, which
// is typically used for full builds and continuous builds.
buildConfigField("String", "BUILD_TIME", "\"${minutesSinceEpoch}\"")
resValue("string", "build_time", "${minutesSinceEpoch}")
...
}
debug {
// Use static values for incremental builds to ensure that
// resource files and BuildConfig aren't rebuilt with each run.
// If they were dynamic, they would prevent certain benefits of
// Instant Run as well as Gradle UP-TO-DATE checks.
buildConfigField("String", "BUILD_TIME", "\"0\"")
resValue("string", "build_time", "0")
}
}
}
...
In your app code, you can access the properties as follows:
...
Log.i(TAG, BuildConfig.BUILD_TIME);
Log.i(TAG, getString(R.string.build_time));
I'm including this here since all of the other solutions appear to be from before the official example.
Solution 9 - Android
I know this is really old, but here's how I did it using ant within eclipse:
build.xml in project root
<project name="set_strings_application_build_date" default="set_build_date" basedir=".">
<description>
This ant script updates strings.xml application_build_date to the current date
</description>
<!-- set global properties for this build -->
<property name="strings.xml" location="./res/values/strings.xml"/>
<target name="init">
<!-- Create the time stamp -->
<tstamp/>
</target>
<target name="set_build_date" depends="init" description="sets the build date" >
<replaceregexp file="${strings.xml}"
match="(<string name="application_build_date">)\d+(</string>)"
replace="<string name="application_build_date">${DSTAMP}</string>" />
</target>
</project>
Then add an application_build_date string to your strings.xml
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_name">your app name</string>
<string name="application_build_date">20140101</string>
...
</resources>
Ensure the ant script is executed as a pre-build activity and you will always have a valid build date available to you within R.string.application_build_date.
Solution 10 - Android
For time stamping and versioning, build.gradle/android/defaultConfig:
def buildDateStamp = new Date().format("yyyyMMdd").toInteger()
versionCode buildDateStamp
versionName "$buildDateStamp"
buildConfigField "String", "BUILD_DATE_STAMP", "\"$buildDateStamp\""
Usage in code: BuildConfig.BUILD_DATE_STAMP
resValue "string", "build_date_stamp", "$buildDateStamp"
Usage in xml: "@string/build_date_stamp"
Caveat: adding HHmm
will cause errors (probably integer overflow)