Game Development Reference
In-Depth Information
With this, we have discussed all of the input processing-related classes of the Android API that
we'll need for game development.
Note As the name implies, the SensorManager class grants you access to other sensors as
well. This includes the compass and light sensors. If you want to be creative, you could come up
with a game idea that uses these sensors. Processing their events is done in a similar way to how
we processed the data of the accelerometer. The documentation at the Android Developers site will
give you more information.
File Handling
Android offers us a couple of ways to read and write files. In this section, we'll check out assets,
how to access the external storage, mostly implemented as an SD card, and shared preferences,
which act like a persistent hash map. Let's start with assets.
Reading Assets
In Chapter 2, we had a brief look at all the folders of an Android project. We identified the
assets/ and res/ folders as the ones where we can put files that should get distributed with
our application. When we discussed the manifest file, we stated that we're not going to use the
res/ folder, as it implies restrictions on how we structure our file set. The assets/ directory is the
place to put all our files, in whatever folder hierarchy we want.
The files in the assets/ folder are exposed via a class called AssetManager . We can obtain a
reference to that manager for our application as follows:
AssetManager assetManager = context.getAssets();
We already saw the Context interface; it is implemented by the Activity class. In real life, we'd
fetch the AssetManager from our activity.
Once we have the AssetManager , we can start opening files like crazy:
InputStream inputStream = assetManager.open("dir/dir2/filename.txt");
This method will return a plain-old Java InputStream , which we can use to read in any sort of
file. The only argument to the AssetManager.open() method is the filename relative to the asset
directory. In the preceding example, we have two directories in the assets/ folder, where the
second one ( dir2/ ) is a child of the first one ( dir/ ). In our Eclipse project, the file would be
located in assets/dir/dir2/ .
Let's write a simple test activity that examines this functionality. We want to load a text file
named myawesometext.txt from a subdirectory of the assets/ directory called texts . The
content of the text file will be displayed in a TextView . Listing 4-7 shows the source for this
awe-inspiring activity.
 
Search WWH ::




Custom Search