From 5f219d3df3a9c953e89e67946d68a2bdc610ad27 Mon Sep 17 00:00:00 2001 From: Vitalii Date: Mon, 7 Mar 2016 21:41:54 +0200 Subject: [PATCH] Fix for External storage for KitKat --- .../afilechooser/utils/FileUtils.java | 47 +++++++++++++++++-- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java b/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java index 25c8008..3a02905 100644 --- a/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java +++ b/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java @@ -283,10 +283,49 @@ else if (isExternalStorageDocument(uri)) { final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { - return Environment.getExternalStorageDirectory() + "/" + split[1]; - } - - // TODO handle non-primary volumes + return Environment.getExternalStorageDirectory() + "/" + split[1]; + }else { + // Below logic is how External Storage provider build URI for documents + // Based on http://stackoverflow.com/questions/28605278/android-5-sd-card-label and https://gist.github.com/prasad321/9852037 + StorageManager mStorageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE); + + try { + Class storageVolumeClazz = Class.forName("android.os.storage.StorageVolume"); + Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList"); + Method getUuid = storageVolumeClazz.getMethod("getUuid"); + Method getState = storageVolumeClazz.getMethod("getState"); + Method getPath = storageVolumeClazz.getMethod("getPath"); + Method isPrimary = storageVolumeClazz.getMethod("isPrimary"); + Method isEmulated = storageVolumeClazz.getMethod("isEmulated"); + + Object result = getVolumeList.invoke(mStorageManager); + + final int length = Array.getLength(result); + for (int i = 0; i < length; i++) { + Object storageVolumeElement = Array.get(result, i); + //String uuid = (String) getUuid.invoke(storageVolumeElement); + + final boolean mounted = Environment.MEDIA_MOUNTED.equals( getState.invoke(storageVolumeElement) ) + || Environment.MEDIA_MOUNTED_READ_ONLY.equals(getState.invoke(storageVolumeElement)); + + //if the media is not mounted, we need not get the volume details + if (!mounted) continue; + + //Primary storage is already handled. + if ((Boolean)isPrimary.invoke(storageVolumeElement) && (Boolean)isEmulated.invoke(storageVolumeElement)) continue; + + String uuid = (String) getUuid.invoke(storageVolumeElement); + + if (uuid != null && uuid.equals(type)) + { + String res =getPath.invoke(storageVolumeElement) + "/" +split[1]; + return res; + } + } + } + catch (Exception ex) { + } + } } // DownloadsProvider else if (isDownloadsDocument(uri)) {