1. 程式人生 > >Android中Assets使用示例

Android中Assets使用示例

Android資源系統(resources system)可以用來打包應用所需的圖片、XML檔案以及其它非Java資源。
除去資源系統外,Android還支援另一種資源打包方式,即assets。

assets可以看作是隨應用打包的微型檔案系統,支援任意層次的檔案目錄結構。

利用Android Studio建立assets目錄的方式是:
在app模組選擇New->Folder->Assets選單項,將出現下圖畫面:

點選finish後,可以看到Apk中出現了新的資源目錄assets:

此時,我們就可以在assets目錄下建立自己需要的目錄。

如果需要獲取assets目錄下的檔案,需要利用到AssetManager,程式碼示例如下:

.........
//assets下的資源目錄名稱
private static final String SOUNDS_FOLDER = "sample_sounds";

public BeatBox(Context context) {
    //利用context的介面得到AssetManager
    mAssetManager = context.getAssets();
    loadSounds();
}

private void loadSounds() {
    String[] soundNames = null;

    try {
        //利用list介面,得到資源目錄下所有的檔名
soundNames = mAssetManager.list(SOUNDS_FOLDER); } catch (IOException ioe) { Log.e(TAG, "Could not list assets", ioe); } if (soundNames != null) { for (String filename : soundNames) { //SOUNDS_FOLDER + "/" + fileName得到基於assets檔案系統的路徑名 mSounds.add(new
Sound(SOUNDS_FOLDER + "/" + filename)); } } } ......

知道檔案的路徑名後,可以利用AssetManager開啟檔案,例如:

...........
try {
    ..........
    InputStream soundData = mAssetManager.open(assetPath);
    ...........
} catch (IOException ioe) {
    ..........
}
..........

此外,利用AssetManager也可以得到檔案描述符,如下:

...........
try {
    ...........
    AssetFileDescriptor assetFd = mAssetManager.openFd(assetPath);
    FileDescriptor fd = assetFd.getFileDescriptor();
    ...........
} catch (IOException ioe) {
    ...........
}
...........