Search code examples
androidkotlinandroid-imageandroid-galleryandroid-camera-intent

Exporting photo to Screenshots doesn't add the photo to the Gallery


My intention is to generate an image and that the user can see it later in the gallery of their mobile phone.

For this I use the following code:

private fun saveToInternalStorage(bitmap: Bitmap) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            saveBitmapAndroidQ(bitmap)
        } else {
            val imagesDir =
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + File.separator + "Screenshots")
                    .toString()
            val image = File(imagesDir, "AppName_${UUID.randomUUID()}.jpg")
            val fos = FileOutputStream(image)

            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            Objects.requireNonNull(fos).close();
            Log.d("exportation", "imagesDir: " + image.toString())
        }
    }

The image is stored in the following URI (and I have checked it manually observing that it is there in the internal storage of my mobile phone):

/storage/emulated/0/Pictures/Screenshots/AppName_113a5010-fbef-41da-b4cc-88f94e25740e.jpg

However, when I open my Gallery App it does not appear anywhere, neither looking for it by name, nor in the "Screenshots" folder, etc. All Screenshots appear except this new image that I have generated with the App.

How can I make the Gallery display my image?

On the other hand, I would like to be able to create a directory within Pictures that has the name of my App, something like:

/storage/emulated/0/Pictures/MyAppFolder/

To store images (and have them appear in the gallery), how can I create my own directory?

Thank you very much in advance!


Solution

  • Thank you blackapps for guiding me on what to use, this is what I missed:

    Manifest

    <manifest [...]>
    
    [...]
    
        <!-- Refresh Media -->
        <protected-broadcast android:name="android.intent.action.MEDIA_MOUNTED" />
    
        <application [...]
    
            <activity [...]
    
                <!-- Refresh Media  -->
                <intent-filter>
                    <action android:name="android.intent.action.MEDIA_MOUNTED" />
                    <data android:scheme="file" />
                </intent-filter>
    
            </activity>
        </application>
    </manifest>
    </manifest>
    

    Fragment

        private fun addGallery(file: File) {
            MediaScannerConnection.scanFile(requireContext(), 
                arrayOf<String>(file.getAbsolutePath()),
                arrayOf("image/jpeg"),
                object : MediaScannerConnection.OnScanCompletedListener {
                    override fun onScanCompleted(path: String?, uri: Uri?) {
                        // Blank
                    }
                })
        }