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

后端 未结 19 2572
温柔的废话
温柔的废话 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条回答
  •  春和景丽
    2020-11-22 03:24

    This is a total hack, but here's what I did...

    So while playing with setting up a DocumentsProvider, I noticed that the sample code (in getDocIdForFile, around line 450) generates a unique id for a selected document based on the file's (unique) path relative to the specified root you give it (that is, what you set mBaseDir to on line 96).

    So the URI ends up looking something like:

    content://com.example.provider/document/root:path/to/the/file

    As the docs say, it's assuming only a single root (in my case that's Environment.getExternalStorageDirectory() but you may use somewhere else... then it takes the file path, starting at the root, and makes it the unique ID, prepending "root:". So I can determine the path by eliminating the "/document/root:" part from uri.getPath(), creating an actual file path by doing something like this:

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // check resultcodes and such, then...
    uri = data.getData();
    if (uri.getAuthority().equals("com.example.provider"))  {
        String path = Environment.getExternalStorageDirectory(0.toString()
                     .concat("/")
                     .concat(uri.getPath().substring("/document/root:".length())));
        doSomethingWithThePath(path); }
    else {
        // another provider (maybe a cloud-based service such as GDrive)
        // created this uri.  So handle it, or don't.  You can allow specific
        // local filesystem providers, filter non-filesystem path results, etc.
    }
    

    I know. It's shameful, but it worked. Again, this relies on you using your own documents provider in your app to generate the document ID.

    (Also, there's a better way to build the path that don't assume "/" is the path separator, etc. But you get the idea.)

提交回复
热议问题