Android 7.0以上和7.0以下获取USB,sdcard路径的方法
16lz
2021-01-23
1 7.0以上路径获取方法
public static List getAllExternalSdcardPath(Context context) { List uDisks = new ArrayList<>(); String systemPath = Environment.getExternalStorageDirectory().getAbsolutePath(); StorageManager mStorageManager; mStorageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE); //获取所有挂载的设备(内部sd卡、外部sd卡、挂载的U盘) if (mStorageManager != null) { List<StorageVolume> volumes = mStorageManager.getStorageVolumes(); Log.e("MainActivity", "size:" + volumes.size()); if (volumes.size() > 0) { try { Class storageVolumeClazz = Class .forName("android.os.storage.StorageVolume"); //通过反射调用系统hide的方法 Method getPath = storageVolumeClazz.getMethod("getPath"); Method isRemovable = storageVolumeClazz.getMethod("isRemovable"); for (int i = 0; i < volumes.size(); i++) { StorageVolume storageVolume = volumes.get(i);//获取每个挂载的StorageVolume //通过反射调用getPath、isRemovable String storagePath = (String) getPath.invoke(storageVolume);//获取路径 if (!storagePath.equalsIgnoreCase(systemPath)) { uDisks.add(storagePath); } boolean isRemovableResult = (boolean) isRemovable.invoke(storageVolume);//是否可移除 String description = storageVolume.getDescription(context); Log.e("MainActivity", " i=" + i + " ,storagePath=" + storagePath + " ,isRemovableResult=" + isRemovableResult + " ,description=" + description); } } catch (Exception e) { e.printStackTrace(); } } } return uDisks; }
2 7.0以下获取路径的方法
public static List getUSBPaths(Context context) {//反射获取路径 String[] paths = null; List<String> data = new ArrayList<>();// include sd and usb devices StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE); try { paths = (String[]) StorageManager.class.getMethod("getVolumePaths", null).invoke(storageManager, null); for (String path : paths) { String state = (String) StorageManager.class.getMethod("getVolumeState", String.class).invoke(storageManager, path); if (state.equals(Environment.MEDIA_MOUNTED) && !path.contains("emulated")) { Log.e("MainActivity", "路径---------->" + path); data.add(path); } } } catch (Exception e) { e.printStackTrace(); } return data; }
更多相关文章
- android 图片处理方法(整理)
- Android 获取截图 并将其保存到本地sd在卡路径
- android 判断当前线程是不是主线程的几种方法
- Android httpClient Get&Post方法
- Android 给textview添加下划线的一种方法(可复用)
- Android中两种实现倒计时的方法
- Android获取系统内核版本的方法
- Android Studio执行Java类的main方法及解决方法