Android app development course Unit 7- + Beyond Android Activities. SMS. Audio, video, camera. Sensors 1
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_RECEIVE 2
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(... ) 3
SMS To receive SMS We need a BroadcastReceive 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( ) from the SmsMessage class 4
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... 5
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 6
Audio, video and camera Android provides support for both audio and video 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: http://developer.android.com/guide/appendix/media-formats.html 7
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 release() 8
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 SurfaceHolder.Callback 9
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(); 10
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);... 11
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(); 12
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. We need one of the following permissions (or both) RECORD_AUDIO RECORD_VIDEO 13
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 14
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... mediarecorder.stop(); 15
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 setpreviewdisplay(surfaceholder) 16
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) { ; 17
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 18
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 <uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" /> 19
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 20
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 onsensorchanged(sensorevent) onaccuracychanged(sensor, accuracy) 21
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); 22
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... 23
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 24