android通過反射得到USB掛載路徑

    public static List<String> getUSBPaths(Context con) {
        String[] paths = null;
        List<String> data = new ArrayList<String>();
        // include sd and usb devices
        StorageManager storageManager = (StorageManager) con
                .getSystemService(Context.STORAGE_SERVICE);
        try {
            paths = (String[]) StorageManager.class.getMethod("getVolumePaths", null).invoke(
                    storageManager, null);
            for (String path : paths) {
                String state = (String) StorageManager.class.getMethod("getVolumeState",
                        String.class).invoke(storageManager, path);
                if (state.equals(Environment.MEDIA_MOUNTED) && !path.contains("emulated")) {
                    data.add(path);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
先貼代碼,之前遇到過一個問題,想得到USB掛載路徑,都是通過系統代碼來實現StorageVolume[] volumes = storageManager.getVolumeList();但此過程需要引入framework.jar因爲StorageVolume這個類是個隱藏類,對於普通app來說,想要獲得USB掛載路徑,用此方式會有一定的麻煩,且不談好不好拿到framework的jar。所以想到通過反射拿到StorageManager中關鍵的二個方法,從中讀取信息來得到USB的掛載路徑。代碼相對簡單,此處就不做註釋了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章