欢迎访问宙启技术站
智能推送

Android 在页面中显示打包日期的实现方法

发布时间:2023-05-17 09:34:40

在 Android 应用中显示打包日期有许多实现方法,可以通过代码或者 Gradle 配置来实现,下面就具体讲解一下实现方法。

1. 通过代码实现

在代码中可以通过以下步骤来获取 APK 的打包日期。

1)获取 APK 的安装包路径

ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
String apkPath = appInfo.sourceDir;

2)通过 ZipFile 类获取 APK 中的 META-INF/MANIFEST.MF 文件并读取其中的 Build-Time 属性。

ZipFile zFile = new ZipFile(new File(apkPath));
ZipEntry entry = zFile.getEntry("META-INF/MANIFEST.MF");
InputStream is = zFile.getInputStream(entry);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while (true) {
    String line = br.readLine();
    if (line == null) {
        break;
    }
    if (line.startsWith("Build-Time: ")) {
        String buildTime = line.substring("Build-Time: ".length());
        // 处理 buildTime
        break;
    }
}

需要注意的是,读取 Build-Time 属性需要在 UI 线程之外的线程中进行。

2. 通过 Gradle 配置实现

在 Gradle 配置中可以通过添加以下代码来实现自动在应用中注入打包日期。

android {
    applicationVariants.all { variant ->
        variant.outputs.all { output ->
            def date = new Date().format("yyyyMMddHHmmss")
            String apkName = output.outputFile.name.replace(".apk", "-${date}.apk")
            output.outputFile = new File(output.outputFile.parent, apkName)
            def manifestFile = variant.processManifest.manifestFile
            def manifestContent = manifestFile.getText('UTF-8')
            manifestContent = manifestContent.replaceAll("versionCode \\d+", "versionCode " + date)
            manifestContent = manifestContent.replaceAll("versionName \\S+", "versionName " + date)
            manifestFile.write(manifestContent, 'UTF-8')
        }
    }
}

这段代码会在每次构建 APK 时在 APK 的名称中加入当时的日期,同时会在 AndroidManifest.xml 文件中修改 versionCode 和 versionName 属性为日期。这样,在应用中就可以通过反射获取 versionCode 或 versionName 属性,然后将其转换为日期格式来获取 APK 的打包日期了。

总结

以上就是 Android 在页面中显示打包日期的实现方法了。这两种方法都比较简单,可以按照自己的需求来选择实现方法。如果只是为了记录版本信息,建议使用 Gradle 配置实现,这样可以避免代码中硬编码版本信息导致修改不便的问题。