Android app development course
Unit
7-+ Beyond Android
Activities
. SMS
. Audio, video, camera
SMS
We can send an SMS through
▸ Android's native client (using an implicit Intent)
Intent smsIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("sms:55512345")); smsIntent.putExtra("sms_body", "Press send to send me");
startActivity(smsIntent); ▸ SmsManager
SmsManager smsManager = SmsManager.getDefault(); String sendTo = "5551234";
String myMessage = "Android supports programmatic SMS messaging!"; smsManager.sendTextMessage(sendTo, null, myMessage, null, null);
▸ We must add the following permissions
SEND_SMS
SMS
SmsManager
▸ sendTextMessage(dstAddress, scAddress, text, sentIntent, deliveryIntent)
▸ sentIntent: PendingIntent launched either when
the SMS has been sent or when it has failed to send
▸ deliveryIntent: PendingIntent launched when we
have the confirmation the SMS has been received
▸ sendMultipartTextMessage( ... ) ▸ sendDataMessage( ... )
SMS
To receive SMS
▸ We need a BroadcastReceiver registered for the Intent
android.provider.telephony.SMS_RECEIVED
▸ The message or messages can be found in the Intent's
extra, “pdus”, which we must convert to SmsMessage
objects
▸ To get the actual text of the message we can use
getMessageBody( )
SMS
public void onReceive(Context _context, Intent _intent) {
if ( intent.getAction().equals(SMS_RECEIVED) ) { SmsManager sms = SmsManager.getDefault(); Bundle bundle = intent.getExtras();
if ( bundle != null ) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); }
for (SmsMessage message : messages) {
String msg = message.getMessageBody();
String to = message.getOriginatingAddress();
// Perform whatever action needed...
Activity 7.1
7.1.1 Create a BroadcastReceiver to receive SMS
7.1.2 Show the contents of the received SMS using a Toast
7.1.3 Create fake SMS through the DDMS perspective to test the receivers correct behavior
Audio, video and camera
Android provides support for both
audio
andvideo
playing and recording. In order to get this done we may use▸ Microphone ▸ Speakers ▸ Camera ▸ Screen
There are formats and codecs with native support in Android. You can found the exhaustive list here:
Audio, video and camera
Playing audio and video
We can play audio and video from
▸ Resource files (raw resources) ▸ File systems (URIs)
▸ Remote streaming (URLs)
Using the MediaPlayer class
▸ We need an instance of MediaPlayer
▸ Call prepare() in the first place to load the player's
buffer
▸ We must release the previous instance by calling
Audio, video and camera
Particularly, in the case of video
▸ It requires a “surface” to play the video on
▸ A Layout containing a VideoView: it already handles a
MediaPlayer instance; therefore we only need to initialize the resource to play
▸ A Layout containing a SurfaceView: must communicate
with the MediaPlayer through a listener that implements
Audio, video and camera
VideoView
VideoView videoView = (VideoView) findViewById(R.id.surface); videoView.setKeepScreenOn(true); videoView.setVideoPath("/sdcard/test2.3gp"); if ( videoView.canSeekForward() ) { videoView.seekTo(videoView.getDuration()/2); } videoView.start(); //Playing... videoView.stopPlayback();
Audio, video and camera
SurfaceView
public class MyActivity extends Activity implements SurfaceHolder.Callback {
private MediaPlayer mMediaPlayer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.main); mMediaPlayer = new MediaPlayer();
SurfaceView surface = (SurfaceView) findViewById(R.id.surface); SurfaceHolder holder = surface.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); holder.setFixedSize(400, 300);
Audio, video and camera
(cont.)
...
public void surfaceCreated(SurfaceHolder holder) { mMediaPlayer.setDisplay(holder);
mMediaPlayer.setDataSource("/sdcard/test2.3gp"); mMediaPlayer.prepare();
mMediaPlayer.start(); }
public void surfaceDestroyed(SurfaceHolder holder) { mMediaPlayer.release();
} }
Audio, video and camera
Recording audio and video
We can use the phone camera through
▸ An implicit Intent to start the native camera app
(both audio and video)
▸ MediaRecorder
▸ Similar to MediaPlayer!
▸ Has methods such as prepare(), start(), stop(),
release(), etc.
Audio, video and camera
MediaRecorder
▸ We need an instance of MediaRecorder ▸ We must configure
▸ Recording source ▸ Destination file
▸ Output format
▸ Coding algorithm
▸ We must prepare the recorder: call prepare() ▸ Use the start() and stop() functions
Audio, video and camera
MediaRecorder (example)
MediaRecorder mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT); mediaRecorder.setOutputFile("/sdcard/myoutputfile.mp4"); mediaRecorder.prepare(); mediaRecorder.start(); // Recording ...
Audio, video and camera
To capture pictures through the phone's camera
‣ We can use already implemented camera apps
startActivityForResult(
new Intent(MediaStore.ACTION_IMAGE_CAPTURE), TAKE_PICTURE )
‣ Manage the camera “manually” through the Camera class
‣ Obtain an instance by calling Camera.open() ‣ Configure it using Camera.Parameters
‣ Obtain a preview using a SurfaceView +
SurfaceHolder.Callback and calling the following method
Audio, video and camera
Example
private void takePicture() {
camera.takePicture(null, null, jpegCallback); }
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
try {
outStream = new FileOutputStream("/sdcard/test.jpg"); outStream.write(data);
outStream.close(); } catch (Exception e) {
Activity 7.2
7.2.1 Create an Activity with two buttons: play and stop
7.2.2 Create a Service bound to the Activity
7.2.3 Start playing and stop an audio file in the res/raw directory by using a MediaPlayer inside the Service
7.2.4 Test that the Service keeps playing the file even if we close the Activity
Sensors
Most Android devices have built-in sensors such as
accelerometer, gyroscope, magnetometers, illumination sensors, etc.
Although typically found in both smartphones and tablets, manufacturers may decide not to include them.
We can enforce our application to be installed and therefore executed only on those devices having a specific sensor
incorporated throught the Manifest file
Sensors
SensorManager
▸ Handle class for all available sensors on the device ▸ We can obtain an instance through
getSystemService(Context.SENSOR_SERVICE)
▸ It can handle up to 12 different sensors (Complete list) ▸ We can retrieve a list of available sensors using
List<Sensor> getSensorList(int type)
▸ To receive sensor readings we must implement the SensorEventListener interface
Sensors
SensorEventListener
▸ Allows us to receive sensor readings and react to these ▸ Is the only way we can retrieve readings from the sensors ▸ We must “register” and “unregister” the listener through
the SensorManager class
▸ register(listener, sensor, timeInterval) ▸ unregisterListener(listener)
▸ We must implement the following methods
Sensors
public class SensorActivity extends Activity implements SensorEventListener {
private final SensorManager mSensorManager;
private final Sensor mAccelerometer;
public SensorActivity() {
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); mAccelerometer = mSensorManager.getDefaultSensor(
Sensor.TYPE_ACCELEROMETER); }
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); }
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this); }
Sensors
(cont)
public void onAccuracyChanged(Sensor sensor, int accuracy) { }
public void onSensorChanged(SensorEvent event) {
float xAxis_lateralA = event.values[0];
float yAxis_longitudinalA = event.values[1];
float zAxis_verticalA = event.values[2]; // Do something with these values...
} }
If you want to know more...
▸ Professional Android Application Development. Chapters
11, 12 and 14
▸ Pro Android. Chapters 18, 19 i 26
▸ Android Developers: Media and Camera ▸ Android Developers: Sensors Overview ▸ Capturing Photos