获取文件的访问时间

Get accessTime of a file

我需要一种方法来获取在 android 中最后一次访问(本地)文件的时间。

我不是说file.lastModified(),而是上次打开的时间(在设备的任何应用程序中查看)。
我有一堆文件只能查看,不能修改,我想删除访问时间最长的文件以释放 space.

我偶然发现 this piece of code 使用 java.nio.file 包:

File file = //file from context.getExternalFilesDir(dirName)
BasicFileAttributes attr = Files.readAttributes(file.toPath(), 
BasicFileAttributes.class);
long accessedAt = attr.lastAccessTime().toMillis();

如前所述 by CommonsWare,使用 java.nio.file、android.system.Os 或其他内置库来实现我的目标将不适用于未来的 android 版本。

所以我最终使用本地数据库 (android room) 来处理对应用程序文件的访问(显然只有在从我自己的应用程序访问时)。

每行有 long lastAccessTimeString filePath 列。
对于每个访问的文件,我插入(如果是第一次)/用 new Date().getTime().

更新其记录

释放 space 时,我查询了按 lastAccessTime ASC 排序的那些记录,因此最旧的将排在第一位。文件删除后,更新相关记录

这种方法之所以可行,是因为所有文件都存储在专用目录中(使用 getExternalFilesDir)并且仅由我的应用程序管理。