Question

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

Was it helpful?

Solution

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);
  }
    });

OTHER TIPS

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);
                }
              });

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"))));

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"))));

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();
}

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())));
                }

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();
 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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top