Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

搞懂安卓內外置 SD 卡:路徑獲取與相容性實戰

編輯:關於 Android 程式設計

最近查看後台監控上報的 App 崩潰日誌時,出現頻率最高的一條,居然是「獲取手機 SD 卡根目錄時崩潰」。為了解決這個惱人的問題,我翻遍了各方資料,也順著 Android API 原始碼摸了一遍。以下把這些心得整理出來,希望能幫到同樣被這個問題困擾的人。

在較早期的 Android(4.1 之前)裡,SD 卡路徑通常以「/sdcard」或「/mnt/sdcard」表示;到了 Jelly Bean 則改為「/storage/sdcard0」,而日後還可能出現多張 SD 卡並存的情況。為了讓舊程式碼仍能正常運作,系統對 sdcard 路徑做了 link 映射。

因此,若希望你的程式碼更健壯、更能適應未來的 Android 版本與新裝置,請一律透過 Environment.getExternalStorageDirectory().getPath() 來取得 SD 卡路徑。

一、通用寫法

 Environment.getExternalStorageDirectory().getPath()

當外置 SD 卡不存在時,這行程式碼取到的是內置 SD 卡的路徑;當外置 SD 卡存在時,取到的則是外置 SD 卡。通常拿到的值會是 /storage/sdcard0。

二、內置 SD 卡又是怎麼一回事

 public static String getSoftwareStorageDirectory() { Map<String,String> sysInfo=System.getenv(); //獲取外置的sd卡 String sd_defult = sysInfo.get("SECONDARY_STORAGE"); return sd_defult; }

用這種寫法拿到的值是 /storage/sdcard1,從序號不難看出,一個是 0、一個是 1。網路上有人提到,這種取值方式在 API 23 中將不再可用——我手邊沒有對應的機型可以驗證,也還沒查閱 API 23 的原始碼,只確定在 API 23 版本中 SECONDARY_STORAGE 這個欄位已被移除。這種寫法其實也是仿照原始碼的取值方式。

在除錯時執行 Map<String,String> sysInfo=System.getenv();,取到的內容大致如下:

 {ANDROID_SOCKET_zygote=9, SECONDARY_STORAGE=/storage/sdcard1, ANDROID_STORAGE=/storage, ANDROID_BOOTLOGO=1, EXTERNAL_STORAGE=/storage/sdcard0, ANDROID_ASSETS=/system/app, ASEC_MOUNTPOINT=/mnt/asec, PATH=/sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin, LOOP_MOUNTPOINT=/mnt/obb, BOOTCLASSPATH=/system/framework/core.jar:..., ANDROID_DATA=/data, ANDROID_PROPERTY_WORKSPACE=8,49664, ANDROID_ROOT=/system, LD_LIBRARY_PATH=/vendor/lib:/system/lib}

對照 API 17 的 Environment 原始碼片段:

 private static final String ENV_EXTERNAL_STORAGE = "EXTERNAL_STORAGE"; private static final String ENV_EMULATED_STORAGE_SOURCE = "EMULATED_STORAGE_SOURCE"; private static final String ENV_EMULATED_STORAGE_TARGET = "EMULATED_STORAGE_TARGET"; private static final String ENV_MEDIA_STORAGE = "MEDIA_STORAGE";
 public UserEnvironment(int userId) { String rawExternalStorage = System.getenv(ENV_EXTERNAL_STORAGE); String rawEmulatedStorageTarget = System.getenv(ENV_EMULATED_STORAGE_TARGET); String rawMediaStorage = System.getenv(ENV_MEDIA_STORAGE); if (TextUtils.isEmpty(rawMediaStorage)) { rawMediaStorage = "/data/media"; } if (!TextUtils.isEmpty(rawEmulatedStorageTarget)) { final String rawUserId = Integer.toString(userId); final File emulatedBase = new File(rawEmulatedStorageTarget); final File mediaBase = new File(rawMediaStorage); mExternalStorage = buildPath(emulatedBase, rawUserId); mMediaStorage = buildPath(mediaBase, rawUserId); } else { if (TextUtils.isEmpty(rawExternalStorage)) { Log.w(TAG, "EXTERNAL_STORAGE undefined; falling back to default"); rawExternalStorage = "/storage/sdcard0"; } mExternalStorage = new File(rawExternalStorage); mMediaStorage = new File(rawMediaStorage); } mExternalStorageAndroidObb = buildPath(mExternalStorage, DIRECTORY_ANDROID, "obb"); mExternalStorageAndroidData = buildPath(mExternalStorage, DIRECTORY_ANDROID, "data"); mExternalStorageAndroidMedia = buildPath(mExternalStorage, DIRECTORY_ANDROID, "media"); }

從上述原始碼可見,String sdcardPath = System.getenv("EXTERNAL_STORAGE"); 取到的同樣是外置 SD 卡。奇怪的是,原始碼裡並沒看到 System.getenv("SECONDARY_STORAGE") 的用法,SECONDARY_STORAGE 這個變數並不存在,那它為何又能使用?這一點著實讓我困惑了老半天。

判斷外置 SD 卡是否存在的原始碼:

 public static String getExternalStorageState() { try { IMountService mountService = IMountService.Stub.asInterface(ServiceManager .getService("mount")); final StorageVolume primary = getPrimaryVolume(); return mountService.getVolumeState(primary.getPath()); } catch (RemoteException rex) { Log.w(TAG, "Failed to read external storage state; assuming REMOVED: " + rex); return Environment.MEDIA_REMOVED; } }

其中還牽涉到一些映射關係:

 private static StorageVolume getPrimaryVolume() { if (sPrimaryVolume == null) { synchronized (sLock) { if (sPrimaryVolume == null) { try { IMountService mountService = IMountService.Stub.asInterface(ServiceManager .getService("mount")); final StorageVolume[] volumes = mountService.getVolumeList(); sPrimaryVolume = StorageManager.getPrimaryVolume(volumes); } catch (Exception e) { Log.e(TAG, "couldn't talk to MountService", e); } } } } return sPrimaryVolume; }

那麼 Android 是如何判斷的呢?

 public boolean getExternalStorageState(){ return Environment.getExternalStorageState().equals(Environment.MEDIA_CHECKING); }

再來看如何判斷是否可讀寫:

 public boolean getExternalStorageStateMOUNTED(){ return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); }

這裡有個容易混淆的地方:判斷「可讀寫」和判斷「是否存在」其實是兩回事。我測試時發現,明明沒插 SD 卡,判斷可讀寫卻仍然通過,可外置 SD 卡根本不存在。所以寫程式的時候,合理的做法應該是先判斷存在、再判斷能否讀寫。

另外還有一個問題:既然外置 SD 卡不存在時,Environment.getExternalStorageDirectory().getPath() 取到的是內置 SD 卡,那我們又該如何判斷內置 SD 卡的讀寫狀態呢?

三、網路上常見的兩種取得外置 SD 卡路徑的方法

方法一:透過解析 mount 指令的輸出。

 public List getExtSDCardPath() { List lResult = new ArrayList(); try { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("mount"); InputStream is = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { if (line.contains("extSdCard")) { String[] arr = line.split(" "); String path = arr[1]; File file = new File(path); if (file.isDirectory()) { lResult.add(path); } } } isr.close(); } catch (Exception e) { } return lResult; }

方法二:先取得預設路徑,再比對 mount 清單。

 public String getExtSDCardPath2() { String sdcard_path = null; String sd_default = Environment.getExternalStorageDirectory() .getAbsolutePath(); if (sd_default.endsWith("/")) { sd_default = sd_default.substring(0, sd_default.length() - 1); } try { Runtime runtime = Runtime.getRuntime(); Process proc = runtime.exec("mount"); InputStream is = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(is); String line; BufferedReader br = new BufferedReader(isr); while ((line = br.readLine()) != null) { if (line.contains("secure")) continue; if (line.contains("asec")) continue; if (line.contains("fat") && line.contains("/mnt/")) { String columns[] = line.split(" "); if (columns != null && columns.length > 1) { if (sd_default.trim().equals(columns[1].trim())) { continue; } sdcard_path = columns[1]; } } else if (line.contains("fuse") && line.contains("/mnt/")) { String columns[] = line.split(" "); if (columns != null && columns.length > 1) { if (sd_default.trim().equals(columns[1].trim())) { continue; } sdcard_path = columns[1]; } } } } catch (Exception e) { e.printStackTrace(); } return sdcard_path; }

我在自己的機型上實測時,取到的值卻都是「/rootfs / rootfs ro,relatime 0 0」這類開頭的內容,根本不是想要的結果。

別忘了在 manifest 中聲明權限:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

最後做個總結:Environment.getExternalStorageDirectory().getPath() 可謂萬能,不論外置還是內置 SD 卡都能取到路徑。不過對 App 而言,往往需要固定一個路徑。我目前採用的是下面這種寫法,先嘗試 SECONDARY_STORAGE,取不到再退回通用寫法:

 public String getSoftwareStorageDirectory() { String strDirectory; Map<String,String> sysInfo=System.getenv(); String sd_defult = sysInfo.get("SECONDARY_STORAGE"); if (!CheckDirectoryExists(sd_defult)) { sd_defult = Environment.getExternalStorageDirectory().getPath(); } return strDirectory; } //判斷檢出目錄是否存在 private boolean CheckDirectoryExists(String fileName) { if (fileName == null || fileName.length()<=0) { return false; } File temFile = new File(fileName); File[] childFiles = null; if (temFile != null) childFiles = temFile.listFiles(); if (childFiles == null) { return false; } File testFile = new File(temFile, "com_testDir"); if (!testFile.exists()) { if (!testFile.mkdir()) { return false; } testFile.delete(); } return true; }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved