I have an open source image picker project on GitHub: ImageSelector. Later there was user feedback that the picture picker on Android 10 phones could not display pictures and could not call the camera to take pictures. So I created an Android 10 emulator myself to try it out and adapt to the project. This blog post explains how to load phone images on Android 10 phones. For compatibility with photography, see my other blog post

Due to file permissions, Android 10 cannot use the image path to load images directly from the phone’s memory card, unless the image is in the app’s private directory, so after Android 10, the following code will not load images.

Bitmap bitmap = BitmapFactory.decodeFile(path);
Copy the code

Bitmap = = null. And there will be a print a BitmapFactory: Unable to decode the stream: Java. IO. FileNotFoundException log.

Images cannot be loaded properly using third-party image loading libraries.

Glide.with(mContext).load(path).into(imageView); // Load failedCopy the code

However, we can load images through image URIs, which is also available in Android 10. First, convert the image path to a URI.

    public static Uri getImageContentUri(Context context, String path) {
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.Media._ID }, MediaStore.Images.Media.DATA + "=? ",
                new String[] { path }, null);
        if(cursor ! = null && cursor.moveToFirst()) { int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID)); Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else{// If the image is not in the phone's shared image database, insert it first.if (new File(path).exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, path);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                returnnull; }}}Copy the code

The image can then be loaded directly through the image URI.

Bitmap bitmap = getBitmapFromUri(context, uri); Public static Bitmap getBitmapFromUri(Context Context, Uri uri) { try { ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver().openFileDescriptor(uri,"r");
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
            parcelFileDescriptor.close();
            return image;
        } catch (Exception e) {
            e.printStackTrace();
        }
        returnnull; Glide. With (mContext).load(uri).into(imageView); //setImageURI
imageView.setImageURI(uri);
Copy the code