Android File Storage

The Android file system gives you the flexibility to scope access to your files as you see fit.

Storing files within application scope
Context.getCacheDir()

This is your applications ephemeral storage directory. These files are can be removed by the system at any time and are removed when you uninstall your application.

Context.getFilesDir()

Store more permanent application files in this directory. They aren’t automatically removed but will be when you uninstall your application.

Context.getExternalFilesDir(type: String)

This is effectively the same as getFilesDir() but optionally allows you to specify a subdirectory.


Storing files publicly
Environment.*

The Environmentprefix gives you access to system environment methods and constants for handling public storage. You can explore the different directory types using the Environment constants.

Environment.getExternalStorageDirectory()

Android recommends not storing your files here as this your users top-level file directory. You should create subdirectories to store your files neatly or use the following function to store in standardized public directories.

Environment.getExternalStoragePublicDirectory(type: String)

This is the method you use the store files publicly. Pass the appropriate directory to the type parameter for the type of file you’re saving. 

A word of caution here: This directory may not exist so you must call .mkdirs() before accessing or storing files here.


Application directory in public directories

You will most likely want to store your files in a subdirectory inside a public directory to make it easy for the user to identify files coming from your application. 

...
val picturesDirectory: File = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
val myPicturesDirectory = new File(picturesDirectory, "Will Connelly")
if (!myPicturesDirectory.exists) {
    myPicturesDirectory.mkdirs()

}

...

In the above example we’ve created a custom directory inside the public pictures directory for the user to easily find photos we’ve stored from our application.


Caveats

Something to remember is that the media scanner does not automatically scan your media as it’s added. If you’re adding a picture or video make sure you send a broadcast to the media scanner so it’s available in your users media player applications immediately.

Conclusion

The Android file system is an extremely flexible system with a lot a options for developers to choose from. When using public directories, store your files in a way the user would expect to see them. Use subdirectories to organise your files and the media scanner to expose media immediately.

Leave a Reply

Your email address will not be published. Required fields are marked *