Last Accessed Time of any file in Android

后端 未结 3 1739
小蘑菇
小蘑菇 2020-12-30 04:21

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 t

相关标签:
3条回答
  • 2020-12-30 04:33

    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.

    Usage:

    Android 5.0+

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

    Using reflection before 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);
    

    Note:

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

    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]
    

    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.

    0 讨论(0)
  • 2020-12-30 04:36

    Try this:

    javaxt.io.File file = new javaxt.io.File("file-path");
    file.getLastAccessTime();
    
    0 讨论(0)
  • 2020-12-30 04:41

    lastModified ()

    import java.io.File;
    import java.util.Date;
    
    public class FileExample {
       public static void main(String[] args) {
    
          File f = null;
          String path;
          long millisec;
          boolean bool = false;
    
          try{      
             f = new File("c:/demo.txt");
    
             bool = f.exists();
    
             if(bool)
             {
                millisec = f.lastModified();
    
                // date and time
                Date dt = new Date(millisec);
    
                // path
                path = f.getPath();
    
                System.out.print(path+" last modified at: "+dt);
             }
          }catch(Exception e){
             e.printStackTrace();
          }
       }
    }
    
    0 讨论(0)
提交回复
热议问题