19

So in my application I at one point save a bunch of images to a temporary folder, and I want them to show up immediately in the Gallery. Off of a reboot, they do, but otherwise they don't.

I've tried using the sendBroadcast method:

 sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, 
     Uri.parse("file://" + Environment.getExternalStorageDirectory())));

But I get a permission error:

E/AndroidRuntime( 2628): java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.MEDIA_MOUNTED from pid=2628, uid=10068

Could I be missing a permission in my AndroidManifest, or is this just no longer supported? Thanks

0

8 Answers 8

21

Code provided by Petrus in another answer works for me on Kitkat (4.4):

MediaScannerConnection.scanFile(this, new String[] { Environment.getExternalStorageDirectory().toString() }, null, new MediaScannerConnection.OnScanCompletedListener() {
/*
 *   (non-Javadoc)
 * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
 */
public void onScanCompleted(String path, Uri uri) 
  {
      Log.i("ExternalStorage", "Scanned " + path + ":");
      Log.i("ExternalStorage", "-> uri=" + uri);
  }
    });
7
  • So when was this no longer supported?
    – NoBugs
    Dec 27, 2013 at 0:23
  • Which device you are using ? It's not working in nexus 5 nor in nexus 4. Can you help ? Feb 7, 2014 at 8:55
  • 1
    This doesn't seem to work for me either on the Nexus 7 running 4.4.2 Feb 18, 2014 at 22:25
  • 1
    Ah, it works fine .. you just need to pass in the path to the actual file you want to scan Feb 18, 2014 at 22:29
  • 1
    Works like a charm on 4.4.2, for multiple files manually add file paths to the string array. You can't add path of the directory.
    – Diljeet
    Jun 4, 2014 at 8:50
9

I tried Environment.getExternalStorageDirectory().toString(), but it didn't find my custom folder.

I just wanted to share my experience to solving this issue.

At the end, I had MediaScannerConnection configured to scan one file at a time and now missing folder that was holding those images showed up. Every time I download each image, I called MediaScannerConnection and file path as Uri instead of folder itself.

Also, many people asked why sendBroadcast stop working on kitkat and the answer is that sendBroadcast was abused and called too many times and causing system to drain battery or slowdown, so they removed the direct call to prevent abuse which makes sense. I was hoping to use above solution to the folder that hold all images, but it didn't work on the folder. I was hoping that finding folder would expose rest of the files within the custom folder, but it didn't in my case. I am hoping to find better answer in the future...

Here's snippet of my code.

MediaScannerConnection.scanFile(ApplicationContext.context, new String[] { imageFile.getPath() }, null,
              new MediaScannerConnection.OnScanCompletedListener() {
                @Override
                public void onScanCompleted(String path, Uri uri) {
                  Log.i(TAG, "Scanned " + path);
                }
              });
1
  • Its works from Android 2.2 to Android 4.4.2 and above
    – Diljeet
    Jun 4, 2014 at 8:52
7

Try this one: after saving your file to folder,write below code

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File("your image path"))));
5

Below code work all device for refreshing the gallery after saving image.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
       Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
       File f1 = new File("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
       Uri contentUri = Uri.fromFile(f1);
       mediaScanIntent.setData(contentUri);
       sendBroadcast(mediaScanIntent);
   } else {
       sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
   }
   sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File("your image path"))));
0
2

Implement MediaScannerConnectionClient and add the below code.Works perfectly in 4.4 :)

MediaScannerConnection conn;

public void startScan(String url) {
    imagepath = url;
    if (conn != null)
        conn.disconnect();
    conn = new MediaScannerConnection(activity.this, activity.this);
    conn.connect();
}

@Override
public void onMediaScannerConnected() {
    try {
        conn.scanFile(imagepath, getMimeType(imagepath));
    } catch (java.lang.IllegalStateException e) {
        //Do something
    }
}

@Override
public void onScanCompleted(String path, Uri uri) {
    conn.disconnect();
}
2

I know its late but try this can working in all versions:

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    Intent mediaScanIntent = new Intent(
                            Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    Uri contentUri = Uri.fromFile(out); //out is your file you saved/deleted/moved/copied
                    mediaScanIntent.setData(contentUri);
                    this.sendBroadcast(mediaScanIntent);
                } else {
                    sendBroadcast(new Intent(
                            Intent.ACTION_MEDIA_MOUNTED,
                            Uri.parse("file://"
                                    + Environment.getExternalStorageDirectory())));
                }
0

Use MediaScannerConnection instead of SendBroadcast..

MediaScannerConnection.MediaScannerConnectionClient(
{
    @Override
    public void onScanCompleted(String path, Uri uri) {

        if (path.equals(**your filename**.getAbsolutePath()))
        {
            Log.i("Scan Status", "Completed");
            Log.i("uri: ",uri.toString());

            conn.disconnect();
        }
    }
    @Override
    public void onMediaScannerConnected()
    {
        // TODO Auto-generated method stub
        conn.scanFile(**your file name**.getAbsolutePath(),null);
    }
});

conn.connect();
-1
 FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
//Gallery Refresh Code         

    MediaScannerConnection.scanFile(getActivity(), new String[] { Environment.getExternalStorageDirectory().toString() }, null, new MediaScannerConnection.OnScanCompletedListener() {
                /*
                 *   (non-Javadoc)
                 * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
                 */
                public void onScanCompleted(String path, Uri uri)
                {
                    Log.i("ExternalStorage", "Scanned " + path + ":");
                    Log.i("ExternalStorage", "-> uri=" + uri);
                }
            });
            out.close();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.