Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ParcelFileDescriptor from URI for image selection in Android

My app is creating an Intent using ACTION_GET_INTENT looking for image mime types. Upon returning I put together a long and elaborate process of checking the intent for data, getting a cursor from the content resolver of the URI, checking the uri.toString() and handling certain URI's different than others. For example "content://com.google.android.gallery3d" would be "content://com.google.android.apps.docs.storage" and so on.

This was getting to be a pain, especially since KitKat came along and introduced more URI's to handle.

BUT then I came along this piece of suggested code on some Google Developer pages related to SAF and KitKat. This seems to work perfectly. I tested in on KitKat, JB, and GB devices on all of the installed "file chooser" kind of apps. It never failed.

**So my question is....is this code solid? Is there anything else to watch for? If this is the preferred method, why so many SO posts on how to deal with the returned Intent/URI from choosing images?

The code sample was found at: https://developer.android.com/guide/topics/providers/document-provider.html Look under the 'Bitmap' section.

try {
        final ParcelFileDescriptor parcelFileDescriptor = myContext.getContentResolver().openFileDescriptor(
                imageUri, "r");
        final FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        final Bitmap bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);
        parcelFileDescriptor.close();
        return bitmap;
    } catch (Exception e) {
        Log.e(tag, "Failed to Parse Image Uri", e);
        throw new Exception("failed to parse image uri");
    }
like image 532
menting311 Avatar asked Dec 26 '13 07:12

menting311


1 Answers

The code which you have mentioned above is the perfect solution for all devices. Because we have a autobackup folders and some specific device uri issues. So if you use the FileDescriptor it will work fine in all devices. I have also used the same code and tested in 11 devices like 2.3.3 version to 4.4.2. Advantage for the above code is: We can select any image from device gallery include autobackup folder. But the existing code which you have mentioned will not work for video selection from gallery(only for autobackup folder).

like image 65
VenSan Avatar answered Sep 30 '22 16:09

VenSan