Login     Sign Up
Innocent Cyril (@admin)
2 months ago
31 Views

Android’s application-neutral APIs provide low-level access to the increasingly diverse hardware commonly available on mobile devices. The ability to monitor and control these hardware fea-tures provides a great incentive for application development on the Android platform.

The hardware APIs available include:

❑ A telephony package that provides access to calls and phone status.

❑ A multimedia playback and recording library.

❑ Access to the device camera for taking pictures and previewing video.

❑ Extensible support for sensor hardware.

❑Accelerometer and compass APIs to monitor orientation and movement.

❑Communications libraries for managing Bluetooth, network, and Wi-Fi hardware.

In this chapter, you’ll take a closer look at some of these hardware APIs. In particular, you’ll learn how to play and record multimedia content including audio, video, and still images, as well as use the camera to capture images and preview and capture live video.

You’ll also learn how to monitor hardware sensors using the Sensor Manager. The accelerom-eter and compass sensors will be used to determine changes in the device orientation and accel-eration — which is extremely useful for creating motion-based User Interfaces — and lets you add new dimensions to your location-based applications.

Finally, you’ll take a closer look at the communication hardware by examining the telephony package for monitoring phone state and phone calls, as well as seeing what’s available in the Bluetooth, networking, and Wi-Fi APIs.

Using the Media APIs

The only modern technology that can compete with mobile phones for ubiquity is the portable digital media player. As a result, the multimedia capabilities of portable devices are a significant consideration for many consumers.

Android’s open platform- and provider-agnostic philosophy ensures that it offers a multimedia library capable of playing and recording a wide range of media formats, both locally and streamed.

Android exposes this library to your applications, providing comprehensive multimedia functionality including recording and playback of audio, video, and still-image media stored locally, within an appli-cation, or streamed over a data connection.

At the time of print, Android supported the following multimedia formats:

❑ JPEG

❑ PNG

❑ OGG

❑ Mpeg 4

❑ 3GPP

❑ MP3

❑ Bitmap

Playing Media Resources

Multimedia playback in Android is handled by the MediaPlayer class. You can play back media stored as application resources, local files, or from a network URI.

To play a media resource, create a new Media Player instance, and assign it a media source to play using the setDataSource method. Before you can start playback, you need to call prepare, as shown in the following code snippet:

String MEDIA_FILE_PATH = Settings.System.DEFAULT_RINGTONE_URI.toString(); MediaPlayer mpFile = new MediaPlayer();

try {

mpFile.setDataSource(MEDIA_FILE_PATH);

mpFile.prepare();

mpFile.start();

}

catch (IllegalArgumentException e) {}

catch (IllegalStateException e) {}

catch (IOException e) {}

Alternatively, the static create methods work as shortcuts, accepting media resources as a parameter and preparing them for playback, as shown in the following example, which plays back an application resource:

MediaPlayer mpRes = MediaPlayer.create(context, R.raw.my_sound);

Note that if you use a create method to generate your MediaPlayer object, prepare is called for you.

Once a Media Player is prepared, call start as shown below to begin playback of the associated media resource.


mpRes.start();

mpFile.start();

The Android Emulator simulates audio playback using the audio output of your development platform.

The Media Player includes stop, pause, and seek methods to control playback, as well as methods to find the duration, position, and image size of the associated media.

To loop or repeat playback, use the setLooping method.

When playing video resources, getFrame will take a screen grab of video media at the specified frame and return a bitmap resource.

Once you’ve finished with the Media Player, be sure to call release to free the associated resources, as shown below:

mpRes.release();

mpFile.release();

Since Android only supports a limited number of simultaneous Media Player objects, not releasing them can cause runtime exceptions.

On Android devices, the Media Player always plays audio using the standard output device — the speaker or connected Bluetooth headset. It’s not currently possible to play audio into a phone conversation.

Recording Multimedia

Multimedia recording is handled by the aptly named MediaRecorder class. To record audio or video, create a new Media Recorder object, as shown in the following code snippet:

MediaRecorder mediaRecorder = new MediaRecorder();

Before you can record any media in Android, your application needs the RECORD_AUDIO and / or RECORD_VIDEO permissions. Add uses-permission tags for each of them, as appropriate, in your application manifest.

<uses-permission android:name=”android.permission.RECORD_AUDIO”/> <uses-permission android:name=”android.permission.RECORD_VIDEO”/>

The ability to record video has been restricted for the version 1.0 release of Android; however, Audio recording is still available.

The Media Recorder can be used to configure the video and audio sources (generally the camera and microphone), output format, video size and frame rate, and the video and audio encoders to use.

The following code snippet shows how to configure a Media Recorder to record audio from the micro-phone using the default format and encoder:

The emulator supports recording of audio using the microphone device attached to your development platform.

Set the audio source. mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

Set the output format. mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);

Set the audio encoders to use. mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);

Once you’ve defined your input source and output format, assign a file to store the recorded media using the setOutputFile method as shown below:

mediaRecorder.setOutputFile(“myoutputfile.mp4”);

The setOutputFile method must be called before prepare and after setOutputFormat or it will throw an Illegal State Exception.

To begin recording, call prepare followed by the start method, as shown below:

mediaRecorder.prepare();

mediaRecorder.start();

When you’re finished, call stop to end the playback, followed by release to free the Media Recorder resources:

mediaRecorder.stop();

mediaRecorder.release();

When recording video, it’s generally considered good practice to display a preview of the recorded video in real time. Using the setPreviewDisplay method, you can assign a Surface to display the video preview.

As with any other resource, media files created by your application will be unavailable to others. As a result, it’s good practice to use the Media Store Content Provider to assign metadata, select a file loca-tion, and publish the recorded media to share recordings with other applications.

To do that, after recording new media create a new ContentValues object to add a new record to the Media Store. The metadata you specify here can include the details including the title, time stamp, and geocoding information for your new media file, as shown in the code snippet below:

ContentValues content = new ContentValues(3); content.put(Audio.AudioColumns.TITLE, “TheSoundandtheFury”);

content.put(Audio.AudioColumns.DATE_ADDED, System.currentTimeMillis() / 1000);

content.put(Audio.Media.MIME_TYPE, “audio/amr”);

You must also specify the absolute path of the media file being added:

content.put(MediaStore.Audio.Media.DATA,

“myoutputfile.mp4”);

Get access to the application’s ContentResolver, and use it to insert this new row into the Media Store as shown in the following code snippet:

ContentResolver resolver = getContentResolver();

Uri uri = resolver.insert(Audio.Media.EXTERNAL_CONTENT_URI, content);

Once the media file has been inserted into the media store you should announce it’s availability using a broadcast Intent as shown below:

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
#Android