Android 获取外置存储卡,检查是否挂载

https://www.jianshu.com/p/de1932ffb1cc

获取所有存储点:

   public String[] getExtSDCardPath() {
       StorageManager storageManager = (StorageManager)getSystemService(Context
               .STORAGE_SERVICE);
       try {
           Class<?>[] paramClasses = {};
           Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths", paramClasses);
           getVolumePathsMethod.setAccessible(true);
           Object[] params = {};
           Object invoke = getVolumePathsMethod.invoke(storageManager, params);
           return (String[])invoke;
       } catch (NoSuchMethodException e1) {
           e1.printStackTrace();
       } catch (IllegalArgumentException e) {
           e.printStackTrace();
       } catch (IllegalAccessException e) {
           e.printStackTrace();
       } catch (Exception e) {
           e.printStackTrace();
       }
       return null;
   }

根据路径来判断具体sd卡是否挂载:

   public static boolean checkMounted(Context context, String mountPoint) {
       if (mountPoint == null) {
           return false;
       }
       StorageManager storageManager = (StorageManager) context
               .getSystemService(Context.STORAGE_SERVICE);
       try {
           Method getVolumeState = storageManager.getClass().getMethod(
                   "getVolumeState", String.class);
           String state = (String) getVolumeState.invoke(storageManager,
                   mountPoint);
           return Environment.MEDIA_MOUNTED.equals(state);
       } catch (Exception e) {
           e.printStackTrace();
       }
       return false;
   }

测试用例:

              String[] data = getExtSDCardPath();
               if (data.length>0){
                   for (String tmp:data){
                       Log.d("tag--->>",tmp+":"+checkMounted(MainActivity.this,tmp));
                   }
               }else{
                     Log.d("tag--->>","未挂载");
               }

猜你喜欢

转载自blog.csdn.net/wxzjn1027/article/details/82378740