如何正确获取安卓外置SD卡的路径

  有时获取安卓的SD卡,实际上是内置的。这个时候,怎样获取外置的

路径呢?经常搜索,吾找到一个办法,共享给大家:

    /**
     * 获取外置卡(可拆卸的)的目录。
     * Environment.getExternalStorageDirectory()获取的目录,有可能是内置卡的。
     * 在高版本上,能访问的外置卡目录只能是/Android/data/{package}。
     */
    private String getAppRootOfSdCardRemovable()
    {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
        {
            return null;
        }

        /**
         * 这一句取的还是内置卡的目录。
         * /storage/emulated/0/Android/data/com.newayte.nvideo.phone/cache
         * 神奇的是,加上这一句,这个可移动卡就能访问了。
         * 猜测是相当于执行了某种初始化动作。
         */
        StorageManager mStorageManager = (StorageManager) 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);
                if ((Boolean) isRemovable.invoke(storageVolumeElement))
                {
                	return path;
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

  希望能给需要的朋友带来帮助。

  祝大家健康顺利。

猜你喜欢

转载自blog.csdn.net/quantum7/article/details/80917167
今日推荐