android中通過java的反射機制獲取U盤名稱

在android項目中實現Windos一樣的U盤效果,需監聽兩個U盤的插入和拔出狀態,並屏蔽本地存儲,使用U盤來下載和上傳文件;
在編輯代碼中碰到一個問題:無法獲取插入U盤的名稱,於是通過java的反射機制來調用源碼的API獲取,方法如下:

    private void checkUdisk(){
        //udisk_insert = false;
        Class volumeInfoClazz = null;
        Method getVolumes = null;
        Method getPath = null;
        Method getUserLabel = null;
        Object[] volumes = null;
        try {
            volumeInfoClazz = Class.forName("android.os.storage.StorageVolume");
            getVolumes = StorageManager.class.getMethod("getVolumeList");
            getPath = volumeInfoClazz.getMethod("getPath");
            getUserLabel = volumeInfoClazz.getMethod("getUserLabel");
            volumes = (Object[])getVolumes.invoke(mStorageManager);
            for (Object vol : volumes) {
                String path = (String) getPath.invoke(vol);
                if (path.indexOf("udisk0")!=-1){
                    String userLabel = (String) getUserLabel.invoke(vol);
//                  if (userLabel!=null){
//                      myApplication.setUserLabel0(userLabel);
//                      udisk_insert = true;
//                  }else {
//                      myApplication.setUserLabel0(null);
//                  }
                }else if (path.indexOf("udisk1")!=-1){
                    String userLabel = (String) getUserLabel.invoke(vol);
//                  if (userLabel!=null){
//                      myApplication.setUserLabel1(userLabel);
//                      udisk_insert = true;
//                  }else {
//                      myApplication.setUserLabel1(null);
//                  }
                }
            }
//          if (udisk_insert){
//              handler_UD.sendEmptyMessage(0);
//          }else {
//              myApplication.setUserLabel0(null);
//              myApplication.setUserLabel1(null);
//              handler_UD.sendEmptyMessage(1);
//          }
        }catch (Exception ex) {
            ex.printStackTrace();
        }
    }

在上面的方法中
volumeInfoClazz = Class.forName("android.os.storage.StorageVolume");
首先通過反射獲取StorageVolume類

getVolumes = StorageManager.class.getMethod("getVolumeList");

然後獲取類中的**getVolumeLis**t方法

getPath = volumeInfoClazz.getMethod("getPath");
            getUserLabel = volumeInfoClazz.getMethod("getUserLabel");

獲取U盤路徑和U盤真實名稱的方法

volumes = (Object[])getVolumes.invoke(mStorageManager);

獲取數組對象

String path = (String) getPath.invoke(vol);

獲取路徑
android中U盤的閃存路徑爲storage/udisk0和storage/udisk1所以在代碼中取出包括關鍵字的對象對應的userLabel也就是U盤名稱

注意事項:
使用的SDK源碼版本不同,會導致方法名不相同,上述方法中使用的是定製源碼,直接複製代碼會導致報錯,使用改方法時,去對應的android\os目錄下找到相應的類,和其中的方法,然後在代碼中通過反射使用。

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