我想从SD卡删除重复的文件。所以我需要访问SD卡文件,这给了我完整的路径。例如。 / storage / 0C08-291C / Android / Docs / file-sample_500kB.rtf
我获得了大于[[SDK级别22]的所有Android版本的SD卡路径,但无法在Android 8 Oreo 版本8.0和版本8.1上获得SD卡访问权限SDK 26和27级]。我正在使用以下方法获取SD卡的根路径:
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;
}
此方法在Android版本8上返回,即使SD卡的安装状态为true。null
我正在使用以下行检查SD卡的状态:
boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
并将SD卡路径作为:
String externalSdCard = getExternalStoragePath(mContext, true);
一旦获得,我正在调用以下方法将GRANT URI PERMISSION转换为SD Card。externalSdCard
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();
}
}
}
要调用。和我的问题是这“如何在Android 8 Oreo上获取SD卡的根路径”我想从SD卡删除重复的文件。所以我需要访问SD卡文件,该文件为我提供了完整路径。例如。 /storage/0C08-291C/Android/Docs/file-sample_500kB.rtf我得到了所有SD卡的路径...takeCardUriPermission(String sdCardRootPath)
方法,我需要SD卡根路径
Environment.getExternalStorageDirectory()