Search code examples
javaandroidstorageandroid-contentprovider

Uri with com.android.externalstorage.documents located on non primary volume


I got a problem. I have Uri which reads something like:

content://com.android.externalstorage.documents/document/[volume_uuid]:[file_path]

I'm able to locate StorageVolume through StorageManager.getStorageVolumes()

If volume is primary: StorageVolume.isPrimary() - I understand that I can parse path as:

Environment.getExternalStorageDirectory() + "/" + file_path;

But how to locate path if volume is not primary? In the end I need to have plain File object referenced through it's absolute path.

P.S. For sure I do have all necessary permission: either static declared through manifest or runtime ones both.


Solution

  • I understand that I can parse path as

    Not reliably. You are assuming a specific internal implementation of code that can vary by device manufacturer and OS version.

    In the end I need to have plain File object referenced through it's absolute path.

    Step #1: Use ContentResolver and openInputStream() to get an InputStream on the contents identified by the Uri

    Step #2: Open a FileOutputStream onto some file that you control (e.g., in getCacheDir())

    Step #3: Copy the content from the InputStream to the FileOutputStream

    Step #4: Use the resulting file, deleting it when it is no longer necessary

    For sure I do have all necessary permission

    For sure you do not, as you have no permissions to access files on removable storage, outside of very specific locations (e.g., the second and subsequent paths returned by getExternalFilesDirs()).