產生編譯日期(Build Date)並自動加入APP內

本文提供給在AOSP內編譯APP, 自動產生編譯日期(Build Date)並自動加入APP內

緣由:
某些板子用的AOSP在產生OTA檔案時會固定的APP編譯後的檔案時間,因此無法網路上用APP內的classes.dex日期來取,所以有額外需求要產生build date。這方法的進階應用是自動抓取目前的APP git資訊並加入生成build檔案,可以用來協助研發人員判讀使用的版本,可參考我之前的文章抓取git commit資訊。

Android.mk內加入下面的define和call,用來自動產生build date檔,並放入APP Assets中

define generate-build-date
  $(info $(LOCAL_PACKAGE_NAME) build date ... $(shell date "+%y%m%d %H%M%S") $(shell mkdir -p $(dir $(1)); LC_TIME=en_US.UTF-8 date "+%y%m%d %H:%M:%S" > $(1) && chmod $(2) $(1)))
endef
$(call generate-build-date,$(LOCAL_PATH)/assets/builddate,0644)

上面這裡使用的build date時間格式是"年月日 時:分:秒"
$ date "+%y%m%d %H:%M:%S"
170119 09:31:11

另外在APP程式碼中加入
final static String UNDEFINED_BUILD_DATE = "UndefinedBuildDate";
private String mBuildDate = UNDEFINED_BUILD_DATE;
private void initAppBuildDate() {
    try {
        mBuildDate = loadBuildDateFromAsset();
    } finally {
        if (mBuildDate == null || mBuildDate.trim().isEmpty()) {
            mBuildDate = UNDEFINED_BUILD_DATE;
        }
    }
}

private String loadBuildDateFromAsset() throws Exception {
    final String buildDateName = "builddate";
    String strBuildDate = null;
    InputStream clsInStream = null;
    try {
        clsInStream = getResources().getAssets().open(buildDateName);
        InputStreamReader clsInReader = new InputStreamReader(clsInStream);
        BufferedReader clsBufReader = new BufferedReader(clsInReader);
        strBuildDate = clsBufReader.readLine();
    } finally {
        if (clsInStream != null) {
            clsInStream.close();
        }
    }
    return strBuildDate;
}
然後在APP的onCreate或者onResume中呼叫initAppBuildDate
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    initAppBuildDate();

留言