Cloud storage is pretty awesome for keeping files available across all of our gadgets while freeing up space on mobile devices. Unfortunately, accessing files in the cloud creates a layer of indirection that may complicate things a little bit, but things become even more complicated when the Storage Access Framework adds yet another layer to the equation. Historically, the SAF could only serve up files that were stored locally, which meant they had to be downloaded and stored before a URI could be returned to the requesting app. That took time and wasn't always necessary, depending on what the client really needed. Android N adds an alternative that may be useful in these situations: virtual files.

Virtual files are effectively placeholders for the real file. Just like any file served through the Storage Access Framework, these are represented as URIs. The primary difference is that the URI doesn't point to an actual file in local storage, but includes enough information so the file can be downloaded and opened if desired. This allows the requesting app to decide if the actual file is necessary or not.

Updating an app to be able to handle virtual files is relatively simple, but it does require a little bit of extra code. The documentation is still a bit sparse and doesn't cover all of the details, but it's enough to get started with testing on Android N. Once the SDK for Android N is finalized and becomes official, the details should be added to the Storage Access Framework documentation.

Preview Documentation

In previous versions of Android, your app could use the Storage Access Framework to allow users to select files from their cloud storage accounts, such as Google Drive. However, there was no way to represent files that did not have a direct bytecode representation; every file was required to provide an input stream.

Android N adds the concept of virtual files to the Storage Access Framework. The virtual files feature allows your DocumentsProvider to return document URIs that can be used with an ACTION_VIEW intent even if they don't have a direct bytecode representation. Android N also allows you to provide alternate formats for user files, virtual or otherwise.

To get a URI for a virtual document in your app, first you create an Intent to open the file picker UI. Since an app cannot directly open a virtual file by using the openInputStream() method, your app does not receive any virtual files if you include the CATEGORY_OPENABLE category.

After the user has made a selection, the system calls the onActivityResult() method. Your app can retrieve the URI of the virtual file and get an input stream, as demonstrated in the code snippet below.

(code removed since it may change)