Wa0139.
Wa0139.
The multimedia features of the Android platform generally fall into three categories: ∙
Still images (recorded with the camera)
∙ Audio (recorded with the microphone, played back with speakers or audio output) ∙ Video (recorded
with the camera and microphone, played back with speakers or audio output)
Multimedia hardware such as a built-in camera, speakers, and audio or video output ports are optional features
for Android devices.
In addition to requiring the appropriate permissions, you can specify which optional features your application
requires within the Android Manifest file.You can do this using the <uses-feature> tag of the Android Manifest
file declare that your application uses the camera. Remember, though, that the <uses feature> tag is not enforced
by the Android platform. Instead, application stores such as the Android Market use this data to filter which
applications to sell to certain devices.
Any application that requests the CAMERA permission is assumed to use all camera features. If your application
accesses the camera, but can function properly without it, you can also set the android:required field of
<uses-feature> to false.However, if your application requires a microphone and a camera with autofocus but not
a flash to be present on the device, you can set the camera features your application requires specifically, like
this:
<uses-feature android:name ”android.hardware.microphone” />
<uses-feature android:name ”android.hardware.camera” />
<uses-feature android:name ”android.hardware.camera.autofocus” />
∙ Calculating the zoom increments (for example, 1x, 2x, 10x) with getZoomRatios()
Depending on the features available for a specific camera, zoom might be digital, optical, or
some combination of the two.
Sharing Images
Storing an image in the local application directory, as demonstrated, might work for some applications; however,
other applications might find it useful if the image goes in the shared image library on the device.The
ContentResolver can be used in conjunction with the MediaStore object to push the image into the shared image
library.The following example demonstrates storing the still image taken by the camera as an image file within
the MediaStore content provider, using the same camera image callback:
Recording Video
Android applications can record video using the MediaRecorder class. Using MediaRecorder is a matter of
following a few simple steps:
1. Instantiate a new MediaRecorder object.
2. Set the video source.
3. Set the video output format.
4. Set the video size to record (optional).
5. Set the video frame rate (optional).
6. Set the video encoder.
7. Set the file to record to. (The extension must match output format.)
8. Set the preview surface.
9. Prepare the object for recording.
10. Start the recording.
11. Stop and release the recording object when finished.
Playing Video
The simplest way to play back video with the Android SDK is to use the VideoView widget along with the
MediaController widget to provide basic video controls.The following is an implementation of an onCreate()
method within an Activity that demonstrates a workable video playback solution:
Recording Audio
The MediaRecorder object of the Android SDK provides audio recording functionality. Using it is a matter of
following a few simple steps you should now find familiar:
1. Instantiate a new MediaRecorder object.
2. Set the audio source.
3. Set the audio format to record with.
4. Set the file format to store the audio in.
5. Set the file to record to.
6. Prepare the object for recording.
7. Start the recording.
8. Stop and release the recording object when finished.
Playing Audio
The MediaPlayer object can be used to play audio.The following steps are required to prepare a file for playback:
1. Instantiate a new MediaPlayer object.
2. Set the path to the file using the setDataSource method.
3. Call the prepare() method of the MediaPlayer object.
4. Call the start() method to begin playback.
5. Playback can then be stopped with a call to the stop() method.
In other cases, applications might need to place a call or send a text message. Phones typically support a Short
Message Service (SMS), which is popular for texting (text messaging). Enabling the capability to leverage this
feature from an application can enhance the appeal of the application and add features that can’t be easily
replicated on a desktop environment. Because many Android devices are phones, applications frequently deal
with phone numbers and the contacts database; some might want to access the phone dialer to place calls or
check phone status information.Adding telephony features to an application enables a more integrated user
experience and enhances the overall value of the application to the users.
Gaining Permission to Access Phone State Information
Let’s begin by looking at how to determine telephony state of the device, including the ability to request the hook
state of the phone, information of the phone service, and utilities for handling and verifying phone numbers.The
TelephonyManager object within the android.telephony package is a great place to start.
Many of the method calls in this section require explicit permission set with the Android application manifest
file.The READ_PHONE_STATE permission is required to retrieve information such as the call state, handset
phone number, and device identifiers or serial numbers.The ACCESS_COARSE_LOCATION permission is
required for cellular location information.
The following block of XML is typically needed in your application’s AndroidManifest.xml file to access basic
phone state information:
<uses-permission
android:name ”android.permission.READ_PHONE_STATE” />
Using SMS
SMS usage has become ubiquitous in the last several years. Integrating messaging services, even if only
outbound, to an application can provide familiar social functionality to the user. SMS functionality is provided to
applications through the android.telephony package.
Sending an SMS
To send an SMS, an application first needs to get an instance of the SmsManager. Unlike other system services,
this is achieved by calling the static method getDefault() of SmsManager: final SmsManager sms
SmsManager.getDefault();
Now that the application has the SmsManager, sending SMS is as simple as a single call:
sms.sendTextMessage( “9995551212”, null, “Hello!”, null, null);
Receiving an SMS
Applications can also receive SMS messages.To do so, your application must register a BroadcastReceiver to
listen for the Intent action associated with receiving an SMS.An application listening to SMS in this way doesn’t
prevent the message from getting to other applications.
Expanding on the previous example, the following code shows how any incoming text message can be placed
within a TextView on the screen:
final TextView receivedMessage (TextView)findViewById(
R.id.received_message);
We extract the phone number the user entered in the EditText field (or the most recently received SMS when
continuing with the previous example).The following code demonstrates how to launch the dialer after the user
presses the Call button:
Button call (Button) findViewById(R.id.call_button);
call.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Uri number Uri.parse(“tel:” +
numberEntry.getText().toString());
Intent dial new Intent(
Intent.ACTION_DIAL, number);
startActivity(dial);
}
});
∙ A stock market application might notify the user when certain stock price targets are met. (Sell now! Before
it’s too late!)
Users appreciate these notifications because they help drive application workflow, reminding the users when they
need to launch the application. However, there is a fine line between just enough and too many
notifications.Application designers need to consider carefully how they should employ the use of notifications so
as not to annoy the user or interrupt them without good reason. Each notification should be appropriate for the
specific application and the event the user is being notified of. For example, an
application should not put out an emergency style notification (think flashing lights, ringing noises, and generally
making a “to-do”) simply to notify the user that his picture has been uploaded to a website or that new content
has been downloaded.
The Android platform provides a number of different ways of notifying the user. Notifications are often
displayed on the status bar at the top of the screen. Notifications may involve
∙ Textual information
∙ Graphical indicators
∙ Sound indicators
Updating Notifications
You don’t want your application’s notifications piling up in the notification bar.Therefore, you might want to
reuse or update notifications to keep the notification list manageable. For example, there is no reason to keep a
notification informing the user that the application is downloading File X when you now want to send another
notification saying File X has finished downloading. Instead, you can simply update the first notification with
new Information
Clearing Notifications
When a user clicks on the notification, the Intent assigned is triggered.At some point after this, the application
might want to clear the notification from the system notifications queue.This is done through a
call to the cancel() method of the NotificationManager object. For instance, the notification we created earlier
could be canceled with the following call: notifier.cancel(NOTIFY_1);
Making Noise
Sometimes, the handset has to make noise to get the user’s attention. Luckily, the Android SDK provides a
means for this using the Notification object. Begin by configuring the audio stream type to use when playing a
sound. Generally, the most useful stream type is STREAM_NOTIFICATION.You can configure the audio stream
type on your notification as follows:
notify.audioStreamType = AudioManager.STREAM_NOTIFICATION;
Now, assign a valid Uri object to the sound member variable and that sound plays when the notification is
triggered.The following code demonstrates how to play a sound that is included as a project resource:
notify.sound = Uri.parse( "android.resource://com.androidbook.simplenotifications/" + R.raw.fallbackring);
Customizing the Notification
Although the default notification behavior in the expanded status bar tray is sufficient for most purposes,
developers can customize how notifications are displayed if they so choose. To do so, developers can use the
RemoteViews object to customize the look and feel of a notification.
The following code demonstrates how to create a RemoteViews object and assign custom text to it:
RemoteViews remote =
new RemoteViews(getPackageName(), R.layout.remote);
remote.setTextViewText(R.id.text1, "Big text here!");
remote.setTextViewText(R.id.text2, "Red text down here!");
notify.contentView = remote;
Designing Useful Notifications
As you can see, the notification capabilities on the Android platform are quite robust—so robust that it is easy to
overdo it and make your application tiresome for the user. Here are some tips for designing useful notifications:
∙ Only use notifications when your application is not in the foreground.When in the foreground, use Toast or
Dialog controls.
∙ Allow the user to determine what types (text, lights, sound, vibration) and frequency of notifications she
will receive, as well as what events to trigger notifications for.
∙ Whenever possible, update and reuse an existing notification instead of creating a new one. ∙
Clear notifications regularly so as not to overwhelm the user with dated information. ∙ When in
doubt, generate “polite” notifications (read: quiet).
∙ Make sure your notifications contain useful information in the ticker, title, and body text fields and launch
sensible intents.
The notification framework is lightweight yet powerful. However, some applications such as alarm clocks or
stock market monitors might also need to implement their own alert windows above and beyond the notification
framework provided. In this case, they may use a background service and launch full Activity windows upon
certain events. In Android 2.0 and later, developers can use the WindowManager.LayoutParams class to enable
activity windows to display, even when the screen is locked with a keyguard.