Android获得内/外置存储卡路径的方法
时间:2021-02-12 08:50:14|栏目:Android代码|点击: 次
我们知道Android上一般都有外置的存储卡,
但是通过Environment.getExternalStorageDirectory()
获取的是内置的存储卡位置 (也有的手机可以在系统中修改默认存储) 那么如何获取外置存储卡的位置呢?
我们可以通过StorageManager来获取多个外置sdcard,代码如下:
StorageManager storageManager = (StorageManager) cxt.getSystemService(Context.STORAGE_SERVICE); try { Method method = StorageManager.class.getDeclaredMethod("getVolumePaths"); method.setAccessible(true); Object result = method.invoke(storageManager); if (result != null && result instanceof String[]) { String[] pathes = (String[]) result; StatFs statFs; for (String path : pathes) { if (!TextUtils.isEmpty(path) && new File(path).exists()) { statFs = new StatFs(path); if (statFs.getBlockCount() * statFs.getBlockSize() != 0) { pathsList.add(path); } } } } } catch (Exception e) { e.printStackTrace(); File externalFolder = Environment.getExternalStorageDirectory(); if (externalFolder != null) { pathsList.add(externalFolder.getAbsolutePath()); } } } return pathsList.toArray(new String[pathsList.size()]);