Internal Services CSE 5236: Mobile Application Development Instructor: Adam C. Champion Course Coordinator: Dr. Rajiv Ramnath 1
Internal Services Communication: Email, SMS and telephony Audio and video: Record and playback Sensors: Accelerometer, light, magnetic, ambient temperature 2
Sending Email public void sendscoresviaemail() { Intent emailintent = new Intent(android.content.Intent.ACTION_SEND); emailintent.putextra( android.content.intent.extra_subject, "Look at my AWESOME TicTacToe Score!"); // Can also fill To: using putextra(, EXTRA_EMAIL) emailintent.settype("plain/text"); emailintent.putextra(android.content.intent.extra_text, firstplayername + " score is " + scoreplayerone + " and " + secondplayername + " score is " + scoreplayertwo); startactivity(emailintent); No classes for email (!): http://groups.google.com/group/android-developers/browse_thread/thread/c58d75c1ccfe598b/ 3bb7cf1ad6fd3a4f. 3
SMS public void sendscoresviasms() { Intent SMSIntent = new Intent(Intent.ACTION_VIEW); SMSIntent.putExtra("sms_body", "Look at my AWESOME TicTacToe Score!" + firstplayername + " score is " + scoreplayerone + " and " + secondplayername + " score is " + scoreplayertwo); SMSIntent.setType("vnd.android-dir/mms-sms"); startactivity(smsintent); Can also use SMS class. See: http://developer.android.com/reference/android/telephony/smsmanager.html Will need: <uses-permission android:name= android.permission.send_sms /> 4
Telephony public void calltictactoehelp() { Intent phoneintent = new Intent(Intent.ACTION_CALL); String phonenumber = "842-822-4357"; // TIC TAC HELP String uri = "tel:" + phonenumber.trim(); phoneintent.setdata(uri.parse(uri)); startactivity(phoneintent); Needs: <uses-permission android:name="android.permission.call_phone"/> 5
1. 2. Playing Audio Example: Setup <?xml version="1.0" encoding="utf-8"?> <LinearLayout > <Button android:text="start Audio"/> <Button android:text="stop Audio /> <Button android:text="record Audio"/> <Button android:text="exit" /> </LinearLayout> Click green Android icon to open Android Device Monitor Highlight device directory: /mnt/shell/emulated/0/sampleaudio.mp3 Select icon with tooltip: Push a file onto the device. CODE ON NEXT SLIDE (Audio.java) 6
String audiofilepath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getPath() + /sampleaudio.mp3 ; Uri audiofileuri = Uri.fromFile(new File(audioFilePath)); public void onclick(view v) { switch(v.getid()) { case R.id.buttonAudioStart: 1 if (!started) { Intent musicintent = new Intent(this, MyPlaybackService.class); musicintent.putextra("uristring", audiofileuri.tostring()); startservice(musicintent); started=true; break; case R.id.buttonAudioStop: stopservice(new Intent(this, MyPlaybackService.class)); started=false; break; case R.id.buttonAudioRecord: // Uses built-in Recorder Intent audiorecordintent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION); startactivityforresult(audiorecordintent, AUDIO_CAPTURED); 2 break; case R.id.buttonAudioExit: finish(); break; protected void onactivityresult (int requestcode, int resultcode, Intent data) { if (resultcode == RESULT_OK && requestcode == AUDIO_CAPTURED) { audiofileuri = data.getdata(); 3 Log.v(TAGACTIVITYAUDIO, "Audio File URI: >" + audiofileuri + "<"); 7
Media Player States Source: https://developer.android.com/reference/android/media/mediaplayer.html 8
Playing Audio: Service <service android:enabled="true android:name=".myplaybackservice /> public class MyPlaybackService extends Service { MediaPlayer player; public IBinder onbind(intent intent) { return null; //Bound services interact with multiple clients public void oncreate() { player = MediaPlayer.create(this, R.raw.sampleaudio); player.setlooping(true); public void onstart(intent intent, int startid) { Bundle extras = intent.getextras(); if(extras!=null){ String audiofileuristring = extras.getstring("uristring"); Uri audiofileuri = Uri.parse(audioFileURIString); try { player.reset(); player.setdatasource(this.getapplicationcontext(), audiofileuri); player.prepare(); catch (Exception e) { player.start(); public void ondestroy() {player.stop(); 9
Handling Video Using VideoView <?xml version="1.0" encoding="utf-8"?> <LinearLayout > <VideoView android:id="@+id/videoview" android:layout_height="175dip" android:layout_width="match_parent" android:layout_gravity="center" /> <Button android:text="start Video"/> <Button android:text="stop Video /> <Button android:text="record Video"/> <Button android:text="exit" /> </LinearLayout> 10
Handling Video: Activity (1) public class Video extends Activity implements OnClickListener{ VideoView videoview = null; static Uri videofileuri = null; public static int VIDEO_CAPTURED = 1; protected void oncreate(bundle savedinstancestate) { videoview = (VideoView) findviewbyid(r.id.videoview); String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getPath() + "/samplevideo.mp4"; File videofile = new File("/mnt/sdcard/samplevideo.3gp"); videofileuri = Uri.fromFile(videoFile); protected void onactivityresult(int requestcode,int resultcode,intent data) { if (resultcode == RESULT_OK && requestcode == VIDEO_CAPTURED) { videofileuri = data.getdata(); 11
Handling Video: Activity (2) public void onclick(view v) { switch(v.getid()){ case R.id.buttonVideoStart: // Load and start the movie videoview.setvideouri(videofileuri); videoview.start(); break; case R.id.buttonVideoRecord: Intent intent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE); startactivityforresult(intent, VIDEO_CAPTURED); break; case R.id.buttonVideoStop: videoview.stopplayback(); break; case R.id.buttonVideoExit: finish(); break; protected void onactivityresult(int requestcode, int resultcode, Intent data) { if (resultcode == RESULT_OK && requestcode == VIDEO_CAPTURED) { videofileuri = data.getdata(); 12
Handling Images: ImageView <?xml version="1.0" encoding="utf-8"?> <LinearLayout > <ImageView android:id="@+id/imageview" android:layout_height="175dip" android:layout_width="match_parent" android:layout_gravity="center" /> <Button android:text="show Image"/> <Button android:text="take Picture"/> <Button android:text="exit" /> </LinearLayout> 13
Handling Images: Code (1) public class Images extends Activity implements OnClickListener{ public int flag = 0; ImageView imageview = null; public static int IMAGE_CAPTURED = 1; static Uri imagefileuri = null; String imagefilepath = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES).getPath() + "/sampleimage.png ; Bitmap imagebitmap = null; static final String TAGIMAGE = "ActivityShowImage ; protected void oncreate(bundle savedinstancestate) { imageview = (ImageView) findviewbyid(r.id.imageview); imagebitmap = BitmapFactory.decodeFile(imageFilePath); 14
Handling Images: Code (2) public void onclick(view v) { switch(v.getid()) { case R.id.buttonImageShow: // Use BitmapFactory to create a bitmap imageview.setimagebitmap(imagebitmap); break; case R.id.buttonImageCapture: Intent cameraintent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startactivityforresult(cameraintent, IMAGE_CAPTURED); break; case R.id.buttonImageExit: finish(); break; 15
Handling Images: Code (3) protected void onactivityresult (int requestcode, int resultcode, Intent cameraintent) { if (resultcode == RESULT_OK && requestcode == IMAGE_CAPTURED) { Bundle extras = cameraintent.getextras(); imagebitmap = (Bitmap) extras.get("data"); imageview.setimagebitmap(imagebitmap); protected void onpause() { Log.d(TAGIMAGE, "Entering onpause"); super.onpause(); System.gc(); //garbage collector // Suggestion: call imagebitmap.recycle() in ondestroy() Known bug: http://code.google.com/p/android/issues/detail?id=8488 16
Sensors Uses: Provide environmental data to app Tailor app to environment Types: Accelerometer, Light sensor, Magnetic, Near-field Example files (from Tic-Tac-Toe): Sensors Activity Sensors.xml Issues: Noisy devices Best tested on a real device. For how to simulate sensors on the emulator see: http://code.google.com/p/openintents/wiki/sensorsimulator 17
Sensors: Listing Available Sensors sensormanager = (SensorManager) getsystemservice(sensor_service); sensorlist = sensormanager.getsensorlist(sensor.type_all); int count=0; for (Sensor sensor : sensorlist) { String sensorname = sensor.getname(); sensordescriptions.append(count+ ". " + sensorname + "\n" + " " + " Ver:" + sensor.getversion() + " Range: " + sensor.getmaximumrange() + " Power: " + sensor.getpower() + " Res: " + sensor.getresolution()); sensordescriptions.append("\n"); count++; 18
Sensors: Registration and Unregistration protected void onresume() { super.onresume(); for (Sensor sensor : sensorlist) { sensormanager.registerlistener(this, sensor, protected void onpause() { super.onpause(); // Stop updates sensormanager.unregisterlistener(this); SensorManager.SENSOR_DELAY_NORMAL); 19
Receiving Sensor Updates public void onsensorchanged(sensorevent event) { String sensoreventstring = sensoreventtostring(event); Log.d(LOGTAG, "--- EVENT Raw Values ---\n" + sensorname + "<\n" + "Distance Last= >" + distanceoflastvalue + "<\n" + "Distance This= >" + distanceofthisvalue + "<\n" + "Change = >" + change + "<\n" + "Percent = >" + percentagechange + "%\n" + "Last value = " + lastvaluestring + "<\n" + sensoreventstring); See complete method on how to filter out noise. 20
Extracting Sensor Parameters private String sensoreventtostring(sensorevent event) { StringBuilder builder = new StringBuilder(); builder.append("sensor: "); builder.append(event.sensor.getname()); builder.append("\naccuracy: "); builder.append(event.accuracy); builder.append("\ntimestamp: "); builder.append(event.timestamp); builder.append("\nvalues:\n"); for (int i = 0; i < event.values.length; i++) { builder.append(" ["); builder.append(i); builder.append("] = "); builder.append(event.values[i]); builder.append("\n"); return builder.tostring(); 21
References Chapter 11: Harnessing the Capabilities of your Android Device from Android SDK 3 Programming for Dummies Services: http://developer.android.com/guide/topics/fundamentals/services.html SMS: http://developer.android.com/reference/android/telephony/smsmanager.html SIP (internet telephony): http://developer.android.com/reference/android/net/sip/package-summary.html MediaPlayer: http://developer.android.com/reference/android/media/mediaplayer.html MediaRecorder: http://developer.android.com/reference/android/media/mediarecorder.html MediaStore class (extract meta-data from media): http://developer.android.com/reference/android/provider/mediastore.html Camera: http://developer.android.com/reference/android/hardware/camera.html BitmapFactory:http://developer.android.com/reference/android/graphics/BitmapFactory.html Bitmap: http://developer.android.com/reference/android/graphics/bitmap.html Sensor: http://developer.android.com/reference/android/hardware/sensor.html SesnorEvent: http://developer.android.com/reference/android/hardware/sensoreventlistener.html 22
Thank You Questions and comments? 23