androidcamerasavegalleryandroid-mediascanner

Capture then Save the Image to Gallery not working Sometimes


I have a method to start the camera and take a photo (working with API 24 and Higher) :

public void invokeCamera()
{
    // create the image Uri
    Uri pictureUri = FileProvider.getUriForFile(getContext(),getContext().getPackageName() + ".provider",createImageFile());


    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    // tell the camera where to save
    intent.putExtra(MediaStore.EXTRA_OUTPUT,pictureUri);

    // permission for saving the image
    intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

    startActivityForResult(intent,CAPTURE_REQ_CODE);
}

creating the image File:

private File createImageFile() {

    File picturesDirectory  = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

    String imgName = "myImageName_0X0Y02_test.jpg";

    return  new File(picturesDirectory.getPath(),"picture" + imgName );

}

this code is working without errors but sometimes i can't see the image in the Gallery , sometimes when i open the gallery after about 10 mins i see it there ! this is weird and i'm confused , am i missing something ?


Solution

  • Since you work with API 24 and higher, I will provide the code for it only. Basically, you need to tell the media scanner that a file was added so it can scan and add it straight away:

    public static void scanMediaForChanges(Context context, File file){
        MediaScannerConnection.scanFile(context,
                new String[]{file.toString()}, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                        Log.i("ExternalStorage", "Scanned " + path + ":");
                        Log.i("ExternalStorage", "-> uri=" + uri);
                    }
                });
    }