APP取得APK的編譯時間
這篇下面的方法是網路上分享的作法,不過在我工作的環境上無效,因為產生軔體時檔案的timestamp被固定成特定時間,但是還是一個值得分享的作法。
這利用的就是build APP的時候內部會產生編譯出的classes.dex這個檔案的timestamp來達成,取得編譯的時間。
當然也可以透過package manager取得APP檔案的路徑,取得lastModified來得知APP放置到系統上的時間。
另外,也可以透過package manager取得lastUpdateTime來得知APP上次更新的時間
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.util.Locale;
import android.content.pm.ApplicationInfo;
private void showPackageInfoTime() {
Log.i(TAG, "showPackageInfoTime()");
try {
PackageManager pm = getPackageManager();
PackageInfo packageInfo = null;
try {
packageInfo = pm.getPackageInfo(getPackageName(), 0);
} catch (NameNotFoundException e) {
Log.e(TAG, "showPackageInfoTime() error: " + e.getMessage());
e.printStackTrace();
}
String installTime = DateUtils.getDate("yyMMdd hh:mm:ss", packageInfo.lastUpdateTime);
String buildTime = DateUtils.getDate("yyMMdd hh:mm:ss", DateUtils.getBuildDate(this));
String apkTime = DateUtils.getDate("yyMMdd hh:mm:ss", DateUtils.getApkDate(this));
Log.i(TAG, "installTime = " + installTime);
Log.i(TAG, "buildTime = " + buildTime);
Log.i(TAG, "apkTime = " + apkTime);
} catch (Exception e) {
Log.e(TAG, "showPackageInfoTime() error: " + e.getMessage());
e.printStackTrace();
}
}
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;
}
public static long getApkDate(Context context) {
try {
ApplicationInfo ai = context.getPackageManager()
.getApplicationInfo(context.getPackageName(), 0);
File file = new File(ai.sourceDir);
long time = file.lastModified();
return time;
} catch (Exception e) {
}
return 0l;
}
}
留言