获得存储卡路径都会用到这个方法:
Environment.getExternalStorageDirectory()
但有些手机的TF卡路径会读不到或者读错。
下面提供一个较好的方法。
三个方法都在StorageManager类中。在使用之前我们需要将其方法反射出来,因为这些方法对外是隐藏的。
String[] getVolumePaths():
返回全部的存储路径,包括内置存储、外置存储和其他挂载路径。要判断某个挂载点的状态就需要用第三个方法。
StorageVolume[] getVolumeList():
会返回如上一个StorageVolume的对象数组,每个存储点的详细数据都在对象中。
String getVolumeState(String mountPoint):
返回以下特定存储点的状态(不止以下状态),没有插入TF卡是会返回 REMOVED 状态。
/** * Unknown storage state, such as when a path isn't backed by known storage * media. * * @see #getExternalStorageState(File) */ public static final String MEDIA_UNKNOWN = "unknown"; /** * Storage state if the media is not present. * * @see #getExternalStorageState(File) */ public static final String MEDIA_REMOVED = "removed";
所以,在手机又TF卡插槽的情况下,无论是否插入TF卡,该返回数组中都会返回TF卡存储路径。所以需要对这些路径进行查看状态在Environment.MEDIA_MOUNTED或Environment.MEDIA_MOUNTED_READ_ONLY。在数组中不止两条数据(第一条是主存,第二条是TF卡),在我的三星手机上会有一个Private的路径返回,需要额外注意:
06-13 10:36:08.418 10993-10993/com.example.test.gifdemo2 E/path: /storage/emulated/0
06-13 10:36:08.418 10993-10993/com.example.test.gifdemo2 E/path: /storage/72AD-2013
06-13 10:36:08.418 10993-10993/com.example.test.gifdemo2 E/path: /storage/Private
之后就需要通过反射,得到隐藏方法并返回数据,下面就开始贴代码:
// 获取主存储卡路径 public String getPrimaryStoragePath(Context context) { try { StorageManager sm = (StorageManager) context.getSystemService(context.STORAGE_SERVICE); Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths", null); String[] paths = (String[]) getVolumePathsMethod.invoke(sm, null); // first element in paths[] is primary storage path return paths[0]; } catch (Exception e) { Log.e("ERROR", "getPrimaryStoragePath() failed", e); } return null; }
// 获取次存储卡路径,一般就是外置 TF 卡了. 不过也有可能是 USB OTG 设备 public String getSecondaryStoragePath(Context context) { try { StorageManager sm = (StorageManager) context.getSystemService(context.STORAGE_SERVICE); Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths", null); String[] paths = (String[]) getVolumePathsMethod.invoke(sm, null); // second element in paths[] is secondary storage path return paths.length <= 1 ? null : paths[1]; } catch (Exception e) { Log.e("ERROR", "getSecondaryStoragePath() failed", e); } return null; }
// 获取存储卡的挂载状态. path 参数传入上两个方法得到的路径 public String getStorageState(Context context, String path) { try { StorageManager sm = (StorageManager) context.getSystemService(context.STORAGE_SERVICE); Method getVolumeStateMethod = StorageManager.class.getMethod("getVolumeState", new Class[] {String.class}); String state = (String) getVolumeStateMethod.invoke(sm, path); return state; } catch (Exception e) { Log.e("ERROR", "getStorageState() failed", e); } return null; }