Java课程设计笔记-Android系统获取所有存储器路径

来源:互联网 发布:广电网络电视怎么使用 编辑:程序博客网 时间:2024/05/19 12:25

在做Android文件管理器的时候遇到这么一个问题:如何获取内置存储+SD卡+其他外部存储(比如U盘)的路径呢?显然Environment.getExternalStorage()方法只能获取内部存储的路径,而且不同安卓机的存储卡挂载路径都各不相同,写固定路径肯定不合适……严格来说,getExternalStorage方法获取的是机器厂商认为的“外部存储”,也是连接USB之后一定可以挂载到电脑上的存储器,有可能是机器的Flash上的一个分区,也有可能是外部SD卡(看到这我只想说贵圈真乱……强迫症受不了这样的API啊)

度娘了一下,发现有一种方法还算比较靠谱,就是通过反射调用StorageManager的getVolumePaths方法,获取所有的存储器挂载点。然而对于手里的狗屎5来说,获取到的路径有些是没有挂载的,还要再判断获取到的路径是否都有效。

于是注意到android.os.StatFs这个类,可以获取文件系统的容量信息。调用StatFs.getAvailableBytes方法可以获取当前文件系统的可用字节数,StatFs.getTotalBytes可以获取文件系统的总容量。然而这个是API 19才可以调用的呵呵……于是只能换成StatFs.getBlockCount() 的返回值与 StatFs.getBlockSize()的返回值相乘,得到总字节数。类似地,也可以用getAvailableBlocks()的返回值与getBlockSize()返回值相乘,得到可用字节数。如果某个路径获取到的总容量为0的话,就可以被认为没有挂载。

代码:

public static final ArrayList<StorageVolumeInfo> getVolumePaths(Context context) {        StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);        Method _getVolumePaths;        ArrayList<StorageVolumeInfo> paths = new ArrayList<>();        try {            _getVolumePaths = storageManager.getClass().getMethod("getVolumePaths");            String[] ret = (String[]) _getVolumePaths.invoke(storageManager);            for (String i : ret) {                StorageVolumeInfo info = new StorageVolumeInfo(i);                if(info.isAvailableVolume())                    paths.add(info);            }        } catch (NoSuchMethodException e) {            e.printStackTrace();        } catch (InvocationTargetException e) {            e.printStackTrace();        } catch (IllegalAccessException e) {            e.printStackTrace();        }        if (paths.size() == 0) {            StorageVolumeInfo info = new StorageVolumeInfo(Environment.getExternalStorageDirectory().getAbsolutePath());            if(info.isAvailableVolume())                paths.add(info);        }        return paths;    }

public class StorageVolumeInfo {    StatFs fs;    /** the path to the storage volume */    public String path;    /** the available size */    public long availableBytes;    /** the total size */    public long totalBytes;    public StorageVolumeInfo(String path){        fs = new StatFs(path);        this.path = path;        this.availableBytes = updateAvailableBytes();        this.totalBytes = updateTotalBytes();    }    /**     * judge a volume is available by the available size     * @return whether the storage volume is mounted     */    public boolean isAvailableVolume(){        return totalBytes > 0;    }    long updateAvailableBytes() {        this.availableBytes = ((long)fs.getAvailableBlocks()) * fs.getBlockSize();        return this.availableBytes;    }    long updateTotalBytes() {        this.totalBytes = ((long)fs.getBlockCount() * fs.getBlockSize());        return this.totalBytes;    }}

还有两分钟断网先不上图了= =

0 0