获取手机和SD卡路径(Android 4.0以上验证过)

来源:互联网 发布:移动数据流量业务序号 编辑:程序博客网 时间:2024/05/22 07:55

1. android 系统内部使用

StorageManager mStorageManager = (StorageManager)getApplicationContext().getSystemService("storage");
  StorageVolume[] storageVolumes = mStorageManager.getVolumeList();
      
        for (StorageVolume volume : storageVolumes) {
         if(volume.isRemovable()){
          //sdcard

          volume.getPath();//外部SD卡存储路径
         }else if(volume.isEmulated()){
          //phone

           volume.getPath();//手机内部存储路径
         }

}

2. 第三方使用(使用反射方式)

private void testStorage(){
 StorageManager storageManager = (StorageManager)getApplicationContext().getSystemService("storage"); 
 try {
           Class<?>[] paramClasses = {};
           Method getVolumeList = StorageManager.class.getMethod("getVolumeList", paramClasses);
           getVolumeList.setAccessible(true);
           Object[] params = {};
           Object[] invokes = (Object[]) getVolumeList.invoke(storageManager, params);
           if (invokes != null) {
               for (int i = 0; i < invokes.length; i++) {
                   Object obj = invokes[i];
                   Method getPath = obj.getClass().getMethod("getPathFile", new Class[0]);
                   File file = (File)getPath.invoke(obj, new Object[0]);
                   if ((file.exists()) && (file.isDirectory())) {
                       Method isRemovable = obj.getClass().getMethod("isRemovable", new Class[0]);
                       Boolean is_removable = (Boolean)isRemovable.invoke(obj, new Object[0]);
                       
                       Method getState = obj.getClass().getMethod("getState", new Class[0]);
                       String storageState = (String)getState.invoke(obj, new Object[0]);
                       Log.i("","path:"+file.getAbsolutePath()+",State:"+storageState+",isRemovable:"+is_removable);
                       if(storageState.equals("mounted") || storageState.equals("removed")){
                       if(is_removable){
                       Log.i("","外部SD卡存储路径 "+file.getAbsolutePath());
                       }else{
                       Log.i("","手机内部存储路径 "+file.getAbsolutePath());
                       }
                       }
                   }
               }
           }
       } catch (NoSuchMethodException e1) {
           e1.printStackTrace();
       } catch (IllegalArgumentException e) {
           e.printStackTrace();
       } catch (IllegalAccessException e) {
           e.printStackTrace();
       } catch (InvocationTargetException e) {
           e.printStackTrace();
       }
}

0 0
原创粉丝点击