Search code examples
androiduripersistent-storage

How can I utilize a persisted URI with apps that don't support ACTION_OPEN_DOCUMENT


My app allows a user to select media (images, video, audio) from whatever is their favorite app for navigating these documents. I then store the URI to that image (rather than downloading the entire image) into a db. On restart of the app, I need to utilize these URIs to pull thumbnails and for images, the complete image from the URIs in order to show them in the app.

I have read the various posts and the docs about using ACTION_OPEN_DOCUMENT initially, granting the appropriate URI permissions, then using takePersistableUriPermission on the resolver.

All that works great. The problem is, there are a lot of apps in the world that manage media choosing that don't support ACTION_OPEN_DOCUMENT, but that do support ACTION_GET_CONTENT.

What I want to do:

  1. Provide a list of apps to allow the user to choose which one they have loaded that can find media for them they want to use in my app.
  2. Use the selected app to choose the media.
  3. Persist the URI of that media to a db so I can utilize it later.

This works perfectly when implementation of the initial intent for selecting the app to use to find the media is ACTION_OPEN_DOCUMENT.

I have no need to perform writes on the media - just open the selection (and utilize the resulting URIs chosen by the user), and store this URI for later usage.

How can I bridge the gap for needing persistent URI with apps that don't support a ACTION_OPEN_DOCUMENT intent?


Solution

  • If you want to use ACTION_GET_CONTENT:

    Step #1: Make a copy of the data to some file that you control (open an InputStream on the content and copy the bytes to a FileOutputStream)

    Step #2: Persist a Uri that points to your copy of the data

    In other words, there is no guarantee that a Uri that you get back from ACTION_GET_CONTENT will be useful in five minutes, let alone five hours, five days, five weeks, etc.

    Alternatively, integrate a file chooser library and limit yourself to files visible to you on the filesystem.