460 likes | 576 Views
Chapter 9 Using the Media Framework and telephony APIs. Lecturer: Prof.Luqun Li ( liluqun@gmail.com ) Teaching Assistants: Fengyou Sun, Haijun Yang, Ting Sun. 1. Telephony APIs. 2. Media Framework. Contents. Sending SMS Messages.
E N D
Chapter 9 Using the Media Framework and telephony APIs Lecturer: Prof.Luqun Li (liluqun@gmail.com) Teaching Assistants: Fengyou Sun, Haijun Yang, Ting Sun
1 Telephony APIs 2 Media Framework Contents
Sending SMS Messages • To send a text message from your application, you need to add the android.permission.SEND_SMS permission to your manifest file and then use the android.telephony.SmsManager class.
Source Code • Layout • Activity
SmsManager.sendTextMessage() • sendTextMessage(String destinationAddress, String smscAddress, String textMsg, PendingIntent sentIntent, PendingIntent deliveryIntent); • You can, however, customize the method so it doesn’t use the default SMS center (the address of the server on the cellular network that will dispatch the SMS message). • You can also implement a customization in which p ending intents are broadcast when the message is sent (or failed) and when a delivery notification has been received.
Using Port Number • Without pending intents, your code can’t tell if the text message was sent successfully or not. While testing, though, you can. • You can use the port number of the other emulator as the destination address.
Monitoring Incoming SMS Messages • Add the android.permission.RECEIVE_SMS permission to the manifest file. • Extend android.content.BroadcastReceiver and then register the receiver in the manifest file.
Source Code • Manifest • BroadcastReceiver
Using Emulator Control • The user interface allows you to send data to the emulator to emulate receiving an SMS message or phone call.
Attention • A broadcast receiver gets high priority in the system, but its task must be finished quickly, and it does not get put into the foreground for the user to see. Therefore, your options are limited. You should not do any direct UI work. Issuing a notification is fine, as is starting a service to continue work there.
Working with SMS Folders • Add read SMS permission (android.permission.READ_SMS ) to the manifest file • Make sure you generate a few SMS messages using the Emulator Control before running the code on the emulator.
Layout • <?xml version="1.0" encoding="utf-8"?> • <!-- This file is /res/layout/sms_inbox.xml --> • <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" • android:orientation="vertical" • android:layout_width="fill_parent" • android:layout_height="fill_parent" > • <TextView android:id="@+id/row" • android:layout_width="fill_parent" • android:layout_height="fill_parent"/> • </LinearLayout>
ListActivity • public class SMSInboxDemo extends ListActivity { • private ListAdapter adapter; • private static final Uri SMS_INBOX = • Uri.parse("content://sms/inbox"); • @Override • public void onCreate(Bundle bundle) { • super.onCreate(bundle); • Cursor c = getContentResolver() • .query(SMS_INBOX, null, null, null, null); • startManagingCursor(c); • String[] columns = new String[] { "body" }; • int[] names = new int[] { R.id.row }; • adapter = new SimpleCursorAdapter(this, R.layout.sms_inbox, • c, columns, names); • setListAdapter(adapter); • } • }
Complete list of SMS folders and URI • All: content://sms/all • Inbox : content://sms/inbox • Sent: content://sms/sent • Draft: content://sms/draft • Outbox: content://sms/outbox • Failed : content://sms/failed • Queued: content://sms/queued • Undelivered: content://sms/undelivered • Conversations: content://sms/conversations
Sending E-mail • Android does not provide APIs for you to send e-mail • Instead, to send e-mail, you have to go through a registered e-mail application.
Launching Application via an Intent • Intent emailIntent=new Intent(Intent.ACTION_SEND); • String subject = "Hi!"; • String body = "hello from android...."; • String[] recipients = new String[]{"aaa@bbb.com"}; • emailIntent.putExtra(Intent.EXTRA_EMAIL, recipients); • emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject); • emailIntent.putExtra(Intent.EXTRA_TEXT, body); • emailIntent.setType("message/rfc822"); • startActivity(emailIntent);
Send an e-mail attachment • emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(myFileName))); • Uri is a reference to the file you want as the attachment.
Working with the Telephony Manager • The easiest way to listen for phone state changes is to implement a broadcast receiver on android.intent.action.PHONE_STATE . You could do this in the same way we listened for incoming SMS messages earlier. • The other way is to use TelephonyManager,be sure to add the android.permission.READ_PHONE_STATE permission to your manifest file
TelephonyManager • Provides access to information about the telephony services on the device. • Retrieve a reference to an instance through Context.getSystemService(Context.TELEPHONY_SERVICE)
PhoneStateListener • A listener class for monitoring changes in specific telephony states on the device, including service state, signal strength, message waiting indicator (voicemail), and others. • Override the methods for the state that you wish to receive updates for, and pass your PhoneStateListener object, along with bitwise-or of the LISTEN_ flags to TelephonyManager.listen().
Source Code • Manifest • Layout • Activity
Using the Emulator Control • To emulate incoming phone calls, you can use Eclipse’s Emulator Control UI
Turn off messages in onPause() • Notice that we tell the TelephonyManager to stop sending us updates in onPause() . It is always important to turn off messages when our activity is being paused. Otherwise, the telephony manager could keep a reference to our object and prevent it from being cleaned up later.
Make an outbound call via Intent • Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:5551212")); • startActivity(intent); • Be sure to add android.permission.CALL_PHONE permission
1 Telephony APIs 2 Media Framework Contents
Using the Media APIs • At the heart of the android.media package is the android.media.MediaPlayer class. • The content for this class can come from the following sources: • Web: You can play content from the Web via a URL. • . apk file : You can play content that is packaged as part of your .apk file. You can package the media content as a resource or as an asset (within the assets folder). • SD card : You can play content that re sides on the de vice’s SD card.
Using SD Cards • You may set the SD card size at the beginning of creation or editing
Using SD Cards • You can add files by using the File Explorer tool in Eclipse.
Playing Audio Content • This application will demonstrate some of the fundamental uses of the MediaPlayer class, such as starting, pausing, restarting, and stopping the media file.
Source Code • Manifest • Layout • Activity
prepareAsync() • The prepareAsync() method returns immediately but sets up a background thread to handle the prepare() method of the MediaPlayer. When the preparation is complete, our activity’s onPrepared() callback is called. This is where we ultimately start the MediaPlayer playing. We have to tell the MediaPlayer who the listener is for the onPrepared() callback, which is why we call setOnPreparedListener() just before the call to prepareAsync().
getCurrentPosition() • You get the current position of the player by calling getCurrentPosition(). You then pause the player by calling pause() . When the player has to be restarted, you call seekTo(), passing in the position obtained earlier from getCurrentPosition(), and then call start()
stop() vs pause() • The MediaPlayer class also contains a stop() method. Note that if you stop the player by calling stop(), you need to prepare the MediaPlayer again before calling start() again. Conversely, if you call pause() , you can call start() again without having to prepare the player. Also, be sure to call the release() method of the media player once you are done using it. In this example, you do this as part of the killMediaPlayer() method.
Playing media local to your .apk file • If you need to include an audio or video file with your application, you should place the file in the /res/raw folder. • private void playLocalAudio()throws Exception • { • mediaPlayer = MediaPlayer.create(this, R.raw.music_file); • mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); • // calling prepare() is not required in this case • mediaPlayer.start(); • } • You should only use the create() method when the media source is local to the device, because it always uses prepare() and not prepareAsync().
Got an audio file on your SD card • static final String AUDIO_PATH = • Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) + "/music_file.mp3";
Understanding the setDataSource() • If you instantiate the MediaPlayer yourself using the default constructor, or if your media content is not accessible through a resource ID or a Uri, you’ll need to call setDataSource() .
Understanding the setDataSource() • private void playLocalAudio_UsingDescriptor() throws Exception { • AssetFileDescriptor fileDesc = getResources().openRawResourceFd( • R.raw.music_file); • if (fileDesc != null) { • mediaPlayer = new MediaPlayer(); • mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); • mediaPlayer.setDataSource(fileDesc.getFileDescriptor(), • fileDesc.getStartOffset(), fileDesc.getLength()); • fileDesc.close(); • mediaPlayer.prepare(); • mediaPlayer.start(); • } • }
Details about the media APIs • Once you set the data source of a MediaPlayer, you cannot easily change it to another one—you’ll have to create a new MediaPlayer or call the reset() method to reinitialize the state of the player. • After you call prepare() , you can call getCurrentPosition(), getDuration() , and isPlaying() to get the current state of the player. You can also call the setLooping() and setVolume() methods after the call to prepare() . If you used prepareAsync(), you should wait until onPrepared() is called before using any of these other methods.
Details about the media APIs • After you call start() , you can call pause() , stop(), and seekTo(). • Every MediaPlayer you create uses a lot of resources, so be sure to call the release() method when you are done with the media player.
Playing Video Content • Playing video requires more effort than playing audio, because there’s a visual component to take care of in addition to t he audio. • Android provides a specialized view control called android.widget.VideoView that encapsulates creating and initializing the MediaPlayer .
Source Code • Manifest • Layout • Activity
Invisible MediaPlayer • Keep in mind that we’re still using a MediaPlayer in this example—we just don’t see it.
Summary • Sending and receiving an SMS message • SMS folders and reading SMS messages • Sending e-mail from an application • TelephonyManager and how to detect an incoming call • Manually putting files onto and getting files from SD cards • Playing audio/video through a MediaPlayer
Interview Questions • 1. Can an SMS message contain more than 140 characters? • 2. True or false: You get an SmsManager instance by calling Context.getSystemService(MESSAGE_SERVICE) . • 3. What permission is needed to write new media files to an SD card?