使用Android 6.0及更高版本,无法编译以下代码。
无法导入android.os.storage.VolumeInfo
需要从getVolumes()API获取volumeInfos。
下面是代码。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
StorageManager sm = ctx.getSystemService(StorageManager.class);
List<VolumeInfo> volumeInfos = sm.getVolumes();
for (VolumeInfo vol : volumeInfos) {
if(vol.type==VolumeInfo.TYPE_PUBLIC
&& (vol.state==VolumeInfo.STATE_MOUNTED || vol.state==VolumeInfo.STATE_MOUNTED_READ_ONLY)){
String desc = sm.getBestVolumeDescription(vol);
boolean isSdCard = desc.toLowerCase().contains("sd");
list.add(new StorageInfo(vol.path, true, isSdCard, vol.fsUuid, vol.fsLabel, desc, isSdCard?0:usbCounter++));
}
}
return list;
}
VolumeInfo不再可用,但是您可以使用StorageVolume
这里有一些提示可以获取有关存储卷的详细信息
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
try {
StorageManager mStorageManager =
(StorageManager) getSystemService(Context.STORAGE_SERVICE);
Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
if (mStorageManager != null) {
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getUuid = storageVolumeClazz.getMethod("getUuid");
Method getPath = storageVolumeClazz.getMethod("getPath");
Method getIsPrimary = storageVolumeClazz.getMethod("isPrimary");
Method getIsRemovable = storageVolumeClazz.getMethod("isRemovable");
Object result = getVolumeList.invoke(mStorageManager);
//Here you can do with the more thing you need in the same way
if (result != null) {
//Iterate All Volumes
for (int i = 0; i < Array.getLength(result); i++) {
Object anStorageObject = Array.get(result, i);
String path = (String) getPath.invoke(anStorageObject);
String uuid = (String) getUuid.invoke(anStorageObject);
Boolean isPrimary = (Boolean) getIsPrimary.invoke(anStorageObject);
Boolean isRemovable = (Boolean) getIsRemovable.invoke(anStorageObject);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}