Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1
Getting At Assets

Assets are accessed using the AssetManager class. You can get an AssetManager from any Context.
Since BeatBox will need one, give it a constructor that takes in a Context as a dependency, pulls out an
AssetManager, and stashes it away.


Listing 20.13  Stashing an AssetManager for safekeeping (BeatBox.java)


public class BeatBox {
private static final String TAG = "BeatBox";


private static final String SOUNDS_FOLDER = "sample_sounds";


private AssetManager mAssets;


public BeatBox(Context context) {
mAssets = context.getAssets();
}
}


When getting at assets, in general you do not need to worry about which Context you are using. In
every situation you are likely to encounter in practice, every Context’s AssetManager will be wired up
to the same set of assets.


To get a listing of what you have in your assets, you can use the list(String) method. Write a
method called loadSounds() that looks in your assets with list(String).


Listing 20.14  Looking at assets (BeatBox.java)


public BeatBox(Context context) {
mAssets = context.getAssets();
loadSounds();
}


private void loadSounds() {
String[] soundNames;
try {
soundNames = mAssets.list(SOUNDS_FOLDER);
Log.i(TAG, "Found " + soundNames.length + " sounds");
} catch (IOException ioe) {
Log.e(TAG, "Could not list assets", ioe);
return;
}
}


AssetManager.list(String) lists filenames contained in the folder path you pass in. By passing in
your sounds folder, you should see every .wav file you put in there.

Free download pdf