2

I'am using the storage access framework to download images to the external sd card. The problem is that these images do not appear in the gallery. I've tried to inform the Android media scanner using an intent by sending the DocumentFile uri, but that doesn't seam to work. Here is how I try to inform the media scanner that a new image is added:

Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(documentFile.getUri());
sendBroadcast(intent);

Is there another way to inform Android that a new image was added? (I've already tried the methods described here, but I couldn't get the real path using those methods)

Community
  • 1
  • 1
TheNetStriker
  • 67
  • 1
  • 5

1 Answers1

1

I've now found a solution. I'am using the following method to get the file path from the DocumentFile. When sending this path to the media scanner the file is scanned correctly:

private static Object[] volumes;

public static Uri getDocumentFileRealPath(Context context, DocumentFile documentFile) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    final String docId = DocumentsContract.getDocumentId(documentFile.getUri());
    final String[] split = docId.split(":");
    final String type = split[0];

    if (type.equalsIgnoreCase("primary")) {
        File file = new File (Environment.getExternalStorageDirectory(), split[1]);
        return Uri.fromFile(file);
    } else {
        if (volumes == null) {
            StorageManager sm=(StorageManager)context.getSystemService(Context.STORAGE_SERVICE);
            Method getVolumeListMethod = sm.getClass().getMethod("getVolumeList", new Class[0]);
            volumes = (Object[])getVolumeListMethod.invoke(sm);
        }

        for (Object volume : volumes) {
            Method getUuidMethod = volume.getClass().getMethod("getUuid", new Class[0]);
            String uuid = (String)getUuidMethod.invoke(volume);

            if (uuid != null && uuid.equalsIgnoreCase(type))
            {
                Method getPathMethod = volume.getClass().getMethod("getPath", new Class[0]);
                String path = (String)getPathMethod.invoke(volume);
                File file = new File (path, split[1]);
                return Uri.fromFile(file);
            }
        }
    }

    return null;
}
TheNetStriker
  • 67
  • 1
  • 5