Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how get a file path by uri which authority is "com.android.externalstorage.documents"

Tags:

android

I want to get a file path through open a file choose by startActivityForResult which intent is Intent.ACTION_GET_CONTENT and setType(* / *), but when I choose open form the "Nexus 5X" item the return uri is "com.android.externalstorage.documents", how to handle this type uri. There are some codes.

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.ACTION_DEVICE_STORAGE_OK, true);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("*/*");
startActivityForResult(intent, FILE_ADD_ACTION_REQUEST_CODE);

screenshot

like image 520
sohnyi Avatar asked Sep 02 '25 02:09

sohnyi


1 Answers

External Storage URIs are of the following form:

content://com.android.externalstorage.documents/root%3Apath

where root is the root of the storage medium, %3A is simply an escaped colon and path is the filesystem path relative to the root (also escaped).

On devices with emulated primary storage (i.e. modern Android devices), the root for primary storage (i.e. /sdcard) is usually called primary. In other cases it seems to be the media ID (4+4 hex digits separated by a hyphen).

You can also try using this (requires API 21 for full functionality):

 public static String getRealPathFromURI_API19(Context context, Uri uri) {
    String filePath = "";

    // ExternalStorageProvider
    String docId = DocumentsContract.getDocumentId(uri);
    String[] split = docId.split(':');
    String type = split[0];

    if ("primary".equalsIgnoreCase(type)) {
        return Environment.getExternalStorageDirectory() + "/" + split[1];
    } else {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            //getExternalMediaDirs() added in API 21
            File[] external = context.getExternalMediaDirs();
            if (external.length > 1) {
                filePath = external[1].getAbsolutePath();
                filePath = filePath.substring(0, filePath.indexOf("Android")) + split[1];
            }
        } else {
            filePath = "/storage/" + type + "/" + split[1];
        }
        return filePath;
}
like image 57
Amit Avatar answered Oct 13 '25 23:10

Amit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!