android 获取sd卡路径的两种步骤

android 获取sd卡路径的两种方法
/**
	 * 方法一
	 * @return
	 */
	public String getSDPath1() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
			return sdDir.toString();
		} else {
			return null;
		}

	}

 

 

1、API>=23 时方法一无效(暂未测试)

2、有些厂商的Rom改动太多,对相关原生API的支持存在问题,这时方法一可能会存在问题。

方法二

public String getSDPath() {
		String path;
		path=getStoragePath(context,false);
		if(path==null){
			path=getStoragePath(context,true);
		}
		return path;
	}
	/**
	 * 获取内部存储和外部存储(内外sd卡)的路径,
	 * 参数 is_removable为false时得到的是内置sd卡路径,为true则为外置sd卡路径。
	 * @param mContext
	 * @param is_removale
	 * @return
	 */
	private static String getStoragePath(Context mContext, boolean is_removale) {  

	      StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
	        Class<?> storageVolumeClazz = null;
	        try {
	            storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
	            Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
	            Method getPath = storageVolumeClazz.getMethod("getPath");
	            Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
	            Object result = getVolumeList.invoke(mStorageManager);
	            final int length = Array.getLength(result);
	            for (int i = 0; i < length; i++) {
	                Object storageVolumeElement = Array.get(result, i);
	                String path = (String) getPath.invoke(storageVolumeElement);
	                boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
	                if (is_removale == removable) {
	                    return path;
	                }
	            }
	        } catch (ClassNotFoundException e) {
	            e.printStackTrace();
	        } catch (InvocationTargetException e) {
	            e.printStackTrace();
	        } catch (NoSuchMethodException e) {
	            e.printStackTrace();
	        } catch (IllegalAccessException e) {
	            e.printStackTrace();
	        }
	        return null;
	}

 

相关内容推荐