//方法一 android10 或者一下的应该可以使用 getVolumes()
int sdCardNum = 0;
int usbDiskNum = 0;
StorageManager mStorageManager = getSystemService(StorageManager.class);
List<VolumeInfo> volumes = mStorageManager.getVolumes();
//Collections.sort(volumes, VolumeInfo.getDescriptionComparator());
for (VolumeInfo vol : volumes) {
if (vol != null) {
DiskInfo disk = vol.getDisk();
if (disk.isSd()) {
sdCardNum++;
}else if(disk.isUsb()){
usbDiskNum++;
}
}
}
//另外不能直接调用getVolumes , 只通过invoke getVolumes 获取得到 List<VolumeInfo>
StorageManager mStorageManager = getSystemService(StorageManager.class);
Class<?> volumeInfoClazz;
Class<?> diskInfoClaszz;
try {
volumeInfoClazz = Class.forName("android.os.storage.VolumeInfo");
Method StorageManager_getVolumes = Class.forName("android.os.storage.StorageManager")
.getMethod("getVolumes");
int sdCardNum = 0;
int usbDiskNum = 0;
List<VolumeInfo> volumeInfos = (List<VolumeInfo>) StorageManager_getVolumes
.invoke(mStorageManager);
for(VolumeInfo volumeInfo: volumeInfos){
DiskInfo diskInfo = volumeInfo.getDisk();
if(diskInfo!=null) {
boolean isSD = diskInfo.isSd();
boolean isUSB = diskInfo.isUsb();
if (isSD) {
sdCardNum++;
}
if(isUSB){
usbDiskNum++;
}
}
}
Log.d("usb","find sdcard:"+sdCardNum);
Log.d("usb","find u-disk:"+usbDiskNum);
}catch (Exception e){
e.printStackTrace();
}
//以上获取的usb u盘数量会在 拔出u盘时不对应,所以可以使用一下方式
//准确获取u盘插入的个数和信息
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> devicelist = usbManager.getDeviceList();
Log.d("usb","u-diask count:"+devicelist.size());