Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

后端 未结 19 2303
温柔的废话
温柔的废话 2020-11-22 02:44

Before KitKat (or before the new Gallery) the Intent.ACTION_GET_CONTENT returned a URI like this

content://media/external/images/media/39

19条回答
  •  梦毁少年i
    2020-11-22 03:32

    Building up on Paul Burke's answer I faced many problems resolving external SD card's URI path as most of the suggested "built-in" functions return paths which do not get resolved to files.

    However, this is my approach of his // TODO handle non-primary volumes.

    String resolvedPath = "";
    File[] possibleExtSdComposites = context.getExternalFilesDirs(null);
    for (File f : possibleExtSdComposites) {
        // Reset final path
        resolvedPath = "";
    
        // Construct list of folders
        ArrayList extSdSplit = new ArrayList<>(Arrays.asList(f.getPath().split("/")));
    
        // Look for folder ""
        int idx = extSdSplit.indexOf(BuildConfig.APPLICATION_ID);
    
        // ASSUMPTION: Expected to be found at depth 2 (in this case ExtSdCard's root is /storage/0000-0000/) - e.g. /storage/0000-0000/Android/data//files
        ArrayList hierarchyList = new ArrayList<>(extSdSplit.subList(0, idx - 2));
    
        // Construct list containing full possible path to the file
        hierarchyList.add(tail);
        String possibleFilePath = TextUtils.join("/", hierarchyList);
    
        // If file is found --> success
        if (idx != -1 && new File(possibleFilePath).exists()) {
            resolvedPath = possibleFilePath;
            break;
        }
    }
    
    if (!resolvedPath.equals("")) {
        return resolvedPath;
    } else {
        return null;
    }
    

    Note it depends on hierarchy which might be different on every phone manufacturer - I have not tested them all (it worked well so far on Xperia Z3 API 23 and Samsung Galaxy A3 API 23).

    Please confirm if it does not perform well elsewhere.

提交回复
热议问题