Android中Assets使用示例

Android资源系统(resources system)可以用来打包应用所需的图片、XML文件以及其它非Java资源。
除去资源系统外,Android还支持另一种资源打包方式,即assets。

assets可以看作是随应用打包的微型文件系统,支持任意层次的文件目录结构。

利用Android Studio创建assets目录的方式是:
在app模块选择New->Folder->Assets菜单项,将出现下图画面:
Android中Assets使用示例_第1张图片

点击finish后,可以看到Apk中出现了新的资源目录assets:
Android中Assets使用示例_第2张图片

此时,我们就可以在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) {
    ...........
}
...........

你可能感兴趣的:(Android开发)