Android中任何文件的上次访问时间 [英] Last Accessed Time of any file in Android

查看:526
本文介绍了Android中任何文件的上次访问时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

file.lastModified()返回上次修改日期.文件似乎没有任何方法来获取lastAccessed日期.有没有办法以编程方式获取android中任何文件的上次访问日期/时间?

file.lastModified() returns the last modified date. File does not seem to have any method to fetch lastAccessed date. Is there a way to programmatically fetch the last accessed date/time of any file in android ?

推荐答案

您可以使用 lstat .这两种方法 android.system.Os.stat(String path) android.system.Os.lstat(String path) ,在Android 5.0中公开.在以前的Android版本上,您将需要使用反射或在Shell中运行命令.

You can get the last access time using stat or lstat. The two methods, android.system.Os.stat(String path) and android.system.Os.lstat(String path), were made public in Android 5.0. On previous Android versions you will need to use reflection or run a command in a shell.

Android 5.0 +

long lastAccessTime = Os.lstat(file.getAbsolutePath()).st_atime;

在Android 5.0之前使用反射

Class<?> clazz = Class.forName("libcore.io.Libcore");
Field field = clazz.getDeclaredField("os");
if (!field.isAccessible()) {
  field.setAccessible(true);
}
Object os = field.get(null);

Method method = os.getClass().getMethod("lstat", String.class);
Object lstat = method.invoke(os, file.getAbsolutePath());

field = lstat.getClass().getDeclaredField("st_atime");
if (!field.isAccessible()) {
  field.setAccessible(true);
}
long lastAccessTime = field.getLong(lstat);


注意:

我认为Android上没有使用上次访问时间.从java.nio文档:


Note:

I don't think last access time is used on Android. From the java.nio documentation:

如果文件系统实现不支持表示最后访问时间的时间戳,则此方法返回实现特定的默认值,通常是最后修改时间或代表时期的FileTime(1970-01-01T00 :00:00Z).

If the file system implementation does not support a time stamp to indicate the time of last access then this method returns an implementation specific default value, typically the last-modified-time or a FileTime representing the epoch (1970-01-01T00:00:00Z).

我测试了使用以下命令来更改上次访问时间:

I tested changing the last access time using the following command:

touch -a [PATH]

这确实改变了我以root用户身份运行命令时的上次访问时间.但是,我认为上次访问时间不会在Android上更新/使用.

This did change the last access time when I ran the command as the root user. However, I don't think the last accessed time is updated/used on Android.

这篇关于Android中任何文件的上次访问时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆