溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在Android中獲得所有存儲設(shè)備位置

發(fā)布時間:2021-05-21 16:04:28 來源:億速云 閱讀:141 作者:Leah 欄目:移動開發(fā)

怎么在Android中獲得所有存儲設(shè)備位置?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

具體代碼如下:

public static List<HomeDirBean> getAllExternalStorage(Context context) {
  List<HomeDirBean> storagePath = new ArrayList<>();
  StorageManager storageManager = (StorageManager) context.getSystemService(STORAGE_SERVICE);
  StorageVolume[] storageVolumes;
  try {
   Method getVolumeList = StorageManager.class.getDeclaredMethod("getVolumeList");
   storageVolumes = (StorageVolume[]) getVolumeList.invoke(storageManager);
   Method getVolumeState = StorageManager.class.getDeclaredMethod("getVolumeState", String.class);
   for (StorageVolume storageVolume : storageVolumes) {
    String desc = storageVolume.getDescription(context);
    Log.i(TAG, "storageVolume name--->" + desc);
    Method getPath = StorageVolume.class.getMethod("getPath");
    String path = (String) getPath.invoke(storageVolume);
    Log.i(TAG, "StoragePath--->" + path);
    //這里需要用StorageManager反射調(diào)用getVolumeState函數(shù),而不應(yīng)該用StorageVolume的getState方法,因為可能會報錯
    String state = (String) getVolumeState.invoke(storageManager, path);
    Log.i(TAG, "storageVolume State--->" + state);
    if (Environment.MEDIA_MOUNTED.equals(state)) {
     HomeDirBean bean = new HomeDirBean(path, desc);
     storagePath.add(bean);
    }
   }
  } catch (Exception e) {
   Log.e(TAG, e.getMessage());
  }
  return storagePath;
 }

這里需要注意,可能有小伙伴會問,既然StorageVolume類有g(shù)etState方法,為啥還要用StorageManager反射調(diào)用getVolumeState方法,并傳入path地址,而在源碼里,StorageManager的getVolumeState的方法的實現(xiàn),也是將path重新創(chuàng)建為StorageVolume類,然后再調(diào)用其getState方法,我們這樣做成這不是多此一舉嗎?

源碼截圖如下:

怎么在Android中獲得所有存儲設(shè)備位置

Android是什么

Android是一種基于Linux內(nèi)核的自由及開放源代碼的操作系統(tǒng),主要使用于移動設(shè)備,如智能手機(jī)和平板電腦,由美國Google公司和開放手機(jī)聯(lián)盟領(lǐng)導(dǎo)及開發(fā)。

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI