Accessing SD Cards

Some Android devices will include a slot for additional flash memory to be plugged in, typically a Secure Digital (SD) card. These memory cards, if present, are much larger than the built-in memory, and thus they're ideal for storing multimegabyte music and video files. They cannot be used for code, and every application can read and write files there.

In Section 5.2, Playing Video, on page 112, we uploaded a sample video file to the /data directory of the emulated device. This is the wrong place for it, since we're not supposed to put large files on the internal file system. So, now I'm going to show you a better way.

The first step is to create and format a virtual SD card that we can "plug in" to the emulator. Luckily we've already done this—if you recall, in Section 1.3, Creating anAVD, on page 23 when we created the "em22" virtual device, we gave it a 64MB virtual SD card as well. You can make it any size you like, but if you make it too small, it may cause the emulator to crash; if you make it too big, you'll just waste space on your computer's disk drive.

Next, let's copy the sample video to the SD card:

C:\> adb push c:\code\samplevideo.3gp /sdcard/samplevideo.3gp

1468 KB/s (369870 bytes in 0.246s)

Then we need to modify the onCreate() method of the Video class to play the movie from the SD card instead of the /data directory:

Download Videov2/src/org/example/video/Video.java

// Load and start the movie video.setVideoPath("/sdcard/samplevideo.3gp"); video.start();

Now try to run the program. The video should play normally.

Note: Starting with Android 1.6, you will need to request the WRITE_ EXTERNAL_STORAGE permission in your manifest file if you want to write to the SD card from your application. Reading from the card doesn't require any special permissions.

Starting with Android 2.2, your application can use the Context.getEx-ternalFilesDir( ) method to get the directory on the external file system where it can place persistent files it owns. Android will delete the files when the application is uninstalled.

0 0

Post a comment