Android 6.0上sdcard和U盤路徑獲取和區(qū)分方法
Android6.0上會根據(jù)卡的種類和卡的掛載狀態(tài)來動態(tài)生成掛載路徑,所以之前寫固定路徑的辦法不可用,最后通過網(wǎng)上查找和分析android源碼,通過反射獲取到路徑,并且進行了正確區(qū)分,代碼如下:
/** * 6.0獲取外置sdcard和U盤路徑,并區(qū)分 * @param mContext * @param keyword SD = "內(nèi)部存儲"; EXT = "SD卡"; USB = "U盤" * @return */ public static String getStoragePath(Context mContext,String keyword) { String targetpath = ""; StorageManager mStorageManager = (StorageManager) mContext .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"); Object result = getVolumeList.invoke(mStorageManager); final int length = Array.getLength(result); Method getUserLabel = storageVolumeClazz.getMethod("getUserLabel"); for (int i = 0; i < length; i++) { Object storageVolumeElement = Array.get(result, i); String userLabel = (String) getUserLabel.invoke(storageVolumeElement); String path = (String) getPath.invoke(storageVolumeElement); if(userLabel.contains(keyword)){ targetpath = path; } } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return targetpath ; }
這里拿到的userLabel就是系統(tǒng)給每個盤的一個label,用來區(qū)分是內(nèi)部存儲、sdcard還是U盤,內(nèi)卡的label固定,但是sdcard和U盤的label是根據(jù)種類,狀態(tài)等信息等動態(tài)生成,所以這里“if(userLabel.contains(keyword)){”沒有用equals。
總結(jié):不懂看源碼
以上這篇Android 6.0上sdcard和U盤路徑獲取和區(qū)分方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Android自定義通用標(biāo)題欄CustomTitleBar
這篇文章主要為大家詳細介紹了Android自定義通用標(biāo)題欄CustomTitleBar,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-11-11Android 中使用ContentObserver模式獲取短信用正則自動填充驗證碼
這篇文章主要介紹了Android 中使用ContentObserver模式獲取短信用正則自動填充驗證碼,首先使用了ContentObserver監(jiān)聽短信,然后從短信中用正則的分組去拿到驗證碼,具體實現(xiàn)代碼大家參考下本文2017-02-02Android自定義ListView實現(xiàn)下拉刷新
這篇文章主要為大家詳細介紹了Android自定義ListView實現(xiàn)下拉刷新的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-07-07Android EasyBarrage實現(xiàn)輕量級彈幕效果
本篇文章主要介紹了Android EasyBarrage實現(xiàn)輕量級彈幕效果,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08Android6.0 storage目錄sd卡存儲的路徑創(chuàng)建詳解
這篇文章主要介紹了Android6.0 storage目錄sd卡存儲的路徑創(chuàng)建的相關(guān)資料,需要的朋友可以參考下2017-01-01