StorageManager獲取U盤掛載狀態

StorageManager是Android SDK中管理存儲設備的一個類。其中的存儲設備分內部存儲和外部存儲,外部存儲可以有SDCard、U盤等其他掛載的外設。
StorageVolume代表的是一個設備信息的數據結構,裏面包含了名稱、路徑、掛載狀態等等信息。
以前獲取設備列表的方法大多是通過反射獲getVolumeList()方法獲取到StorageVolume[]數組,但是現在發現完全沒有必要的,通過getStorageVolumes()方法便可以獲取到StorageVolume的集合。只是在取StorageVolume裏面的字段的時候,像Path、ID這些屬性的get方法是隱藏的,需要使用反射來獲取。示例代碼如下:

 mStorageManager = getSystemService(StorageManager.class);
        List<StorageVolume> volumeList = mStorageManager.getStorageVolumes();
        for (StorageVolume volume : volumeList) {
            if (null != volume && volume.isRemovable()) {
                String label = volume.getDescription(this);   //這個其實就是U盤的名稱
                String status = volume.getState();                   //設備掛載的狀態,如:mounted、unmounted
                boolean isEmulated = volume.isEmulated();            //是否是內部存儲設備
                boolean isRemovable = volume.isRemovable();          //是否是可移除的外部存儲設備
                String mPath="";                                     //設備的路徑


                try {
                    Class myclass = Class.forName(volume.getClass().getName());
                    Method getPath =  myclass.getDeclaredMethod("getPath",null);
                    getPath.setAccessible(true);
                    mPath = (String) getPath.invoke(volume);

                    Log.i(TAG,"name:"+label);
                    Log.i(TAG,"status:"+status);
                    Log.i(TAG,"isEmulated:"+isEmulated);
                    Log.i(TAG,"isRemovable:"+isRemovable);
                    Log.i(TAG,"mPath:"+mPath);

                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }catch (InvocationTargetException e) {
                    e.printStackTrace();
                }catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章