0

Required Behaviour: I use following code to save images, and want to show them up in gallery(as we get to see images from whatsapp).

boolean downloadImage(Bitmap image) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, "Download started..", Toast.LENGTH_SHORT).show();
            }
        });
        ContentResolver resolver = getApplicationContext().getContentResolver();
        Uri imageCollection;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            imageCollection = MediaStore.Images.Media
                    .getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
        } else {
            imageCollection = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        }
        String imgName = "IMG_"+System.currentTimeMillis()+".jpg";
        ContentValues imgDetails = new ContentValues();
        imgDetails.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        imgDetails.put(MediaStore.Images.Media.DISPLAY_NAME, imgName);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            imgDetails.put(MediaStore.Images.Media.IS_PENDING, 1);
            imgDetails.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/DownloaderApp");
        }
        Uri imgUri = resolver.insert(imageCollection, imgDetails);
        try {
            OutputStream outputStream = resolver.openOutputStream(imgUri);
            boolean saveResult = image.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
            outputStream.close();
            imgDetails.clear();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                imgDetails.put(MediaStore.Images.Media.IS_PENDING, 0);
            }
            resolver.update(imageCollection, imgDetails, null, null);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(
                            MainActivity.this,
                            (saveResult) ?"Image Path: "+imgUri.getPath() :"Failed to save image!",
                            Toast.LENGTH_SHORT).show();
                }
            });
            outputStream.close();
            return saveResult;
        } catch(Exception e) {
            e.printStackTrace();
            return false;
        }
    }

Current Situation: I can see images getting saved in File Manager at exact location DCIM/DownloaderApp, but these pictures do not appear in gallery, i.e. they are not publically visibe through MediaStore API(what I feel).
Targetted Android: Android 10

I know, I can use android:requestLegacyExternalStorage="true" in manifest. But I want the app to be perfectly compatible with android 11 as well. So don't want to do this.

0 Answers0