I need a method of getting the last time a (local) file has been accessed in android.
I don't mean file.lastModified()
, but the last time it had been opened (viewed in any app of the device).
I have bunch of files that are only viewed, not modified, and i want to delete the files that has been accessed longest time ago to free up space.
I stumbled across this piece of code using java.nio.file
package:
File file = //file from context.getExternalFilesDir(dirName)
BasicFileAttributes attr = Files.readAttributes(file.toPath(),
BasicFileAttributes.class);
long accessedAt = attr.lastAccessTime().toMillis();
Can someone confirm that this actually works and retrieve the last time the file has been accessed?
Is this even possible to achieve in android?
This code requires API level 26 and above, is there any way to so with 21 <= API level < 26 ?
As mentioned here by CommonsWare, using java.nio.file, android.system.Os or other built in libraries to achieve my goal won't work well with future android versions.
So i ended up using a local DB (android room) for handling the access to app's files (only when accessing from my own app obviously).
Each row has long lastAccessTime
and String filePath
columns.
For each file accessed i inserted(if it's the first time)/updated its record with new Date().getTime()
.
When freeing up space, i queried for those records ordered by lastAccessTime ASC
, so the oldest will be first. After a file was deleted, updated the relevant record.
This approach was possible because all of the files were stored in a dedicated directory (using getExternalFilesDir) and were managed only by my application.