I want to delete duplicate files from SD Card. So i need to access SD Card files which give me the full path. eg. /storage/0C08-291C/Android/Docs/file-sample_500kB.rtf
I got the SD Card path for all Android version greater than SDK level 22 but not able to get SD Card access on Android 8 Oreo Version 8.0 and Version 8.1 SDK level 26 and 27.
I am using below method to get SD Card root path:
public static String getExternalStoragePath(Context mContext, boolean is_removable) {
StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
Class<?> storageVolumeClazz = null;
try {
storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getPath = storageVolumeClazz.getMethod("getPath");
Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
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 path = (String) getPath.invoke(storageVolumeElement);
boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
if (is_removable == removable) {
return path;
}
}
} catch (ClassNotFoundException | InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
This method return null on Android Version 8 even if SD card mounted status is true.
I am checking SD Card status by using below line:
boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
And getting the SD Card path as:
String externalSdCard = getExternalStoragePath(mContext, true);
Once i got the externalSdCard i am calling the below method to GRANT URI PERMISSION to SD Card.
public void takeCardUriPermission(String sdCardRootPath) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
File sdCard = new File(sdCardRootPath);
StorageManager storageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
StorageVolume storageVolume = storageManager.getStorageVolume(sdCard);
Intent intent = null;
if (storageVolume != null) {
intent = storageVolume.createAccessIntent(null);
}
try {
startActivityForResult(intent, REQUEST_CODE_OPEN_DOCUMENT_TREE);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
}
To call the takeCardUriPermission(String sdCardRootPath) method i required SD Card root path. and my question is this "How to get root path of SD Card on Android 8 Oreo"