StorageManager
StorageManager is the interface to the systems storage service. The storage manager handles storage-related items such as Opaque Binary Blobs (OBBs).
OBBs contain a filesystem that maybe be encrypted on disk and mounted on-demand from an application. OBBs are a good way of providing large amounts of binary assets without packaging them into APKs as they may be multiple gigabytes in size. However, due to their size, they're most likely stored in a shared storage pool accessible from all programs. The system does not guarantee the security of the OBB file itself: if any program modifies the OBB, there is no guarantee that a read from that OBB will produce the expected output.
Get an instance of this class by calling getSystemService(java.lang.String)
with an argument of STORAGE_SERVICE
.
從Android 2.3開始新增了一個OBB文件系統和StorageManager類用來管理外部存儲上的數據安全。
如果我們設計一款資源包含比較多的游戲,可能你會發現最終生成的APK文件可能高達300MB,但是APK文件很大導致Android系統無法正常安裝,而這么大其實都是游戲中用到的資源文件,我們放到SD卡上可能其他應用也可以訪問,比如說系統的圖片管理器會索引游戲中的圖片資源,而音樂播放器也會索引資源中的音樂,所以Android 2.3的OBB文件(Opaque Binary Blob)可以很好的解決大文件在SD卡上分離出APK文件,同時別的程序沒有權限訪問這樣一種隔離的文件系統。
android.os.storage.StorageManager類的實例化方法需要使用 getSystemService(Contxt.STORAGE_SERVICE)才可以,eoe再次提醒這是一個API Level至少為9才能調用的類,注意SDK版本以及目標設備的固件。
我們知道android上一般都有外置的存儲卡,
但是通過Environment.getExternalStorageDirectory()獲取的是內置的存儲卡位置 (也有的手機可以在系統中修改默認存儲) 那么如何獲取外置存儲卡的位置呢?
通過StorageManager來獲取多個sdcard,比使用cat /proc/mounts要好:
public static String[] getStoragePaths(Context cxt) { List<String> pathsList = new ArrayList<String>(); if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.GINGERBREAD) { StringBuilder sb = new StringBuilder(); try { pathsList.addAll(new SdCardFetcher().getStoragePaths(new FileReader("/proc/mounts"), sb)); } catch (FileNotFoundException e) { e.printStackTrace(); File externalFolder = Environment.getExternalStorageDirectory(); if (externalFolder != null) { pathsList.add(externalFolder.getAbsolutePath()); } } } else { StorageManager storageManager = (StorageManager) cxt.getSystemService(Context.STORAGE_SERVICE); try { Method method = StorageManager.class.getDeclaredMethod("getVolumePaths"); method.setAccessible(true); Object result = method.invoke(storageManager); if (result != null && result instanceof String[]) { String[] pathes = (String[]) result; StatFs statFs; for (String path : pathes) { if (!TextUtils.isEmpty(path) && new File(path).exists()) { statFs = new StatFs(path); if (statFs.getBlockCount() * statFs.getBlockSize() != 0) { pathsList.add(path); } } } } } catch (Exception e) { e.printStackTrace(); File externalFolder = Environment.getExternalStorageDirectory(); if (externalFolder != null) { pathsList.add(externalFolder.getAbsolutePath()); } } } return pathsList.toArray(new String[pathsList.size()]); }