• No results found

Android app development course

N/A
N/A
Protected

Academic year: 2021

Share "Android app development course"

Copied!
24
0
0

Loading.... (view fulltext now)

Full text

(1)

Android app development course

Unit

7-+ Beyond Android

Activities

. SMS

. Audio, video, camera

(2)

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

(3)

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( ... )

(4)

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( )

(5)

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...

(6)

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

(7)

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:

(8)

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

(9)

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

(10)

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();

(11)

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);

(12)

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();

} }

(13)

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.

(14)

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

(15)

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 ...

(16)

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

(17)

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) {

(18)

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

(19)

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

(20)

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

(21)

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

(22)

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); }

(23)

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...

} }

(24)

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

References

Related documents

Although total labor earnings increase with the unskilled unions’ bargaining power, we can say nothing when the increase in production is due to stronger skilled unions, since

Using a nationwide database of hospital admissions, we established that diverticulitis patients admitted to hospitals that encounter a low volume of diverticulitis cases have

(1872–2016) of the floodplain vegetation of a segment of the heavily regulated upper Rhine River to different static approaches for the es- timation of its PNV a) a statistical

82 In Henry, the Court created a newly-worded test: &#34;By intentionally creating a situation likely to induce [the defendant] to make incriminating statements

The Seckford Education Trust and our schools should be environments in which pupils and students or their parents/carers can feel comfortable and confident

We agree that during the Period of Cover, should Your Product suffer Accidental Damage, Accidental Loss or Theft, We will elect at Our option, to repair the Product or if it is

Most algorithms for large item sets are related to the Apri- ori algorithm that will be discussed in Chapter IV-A2. All algorithms and methods are usually based on the same

3This result is explained by the fact that under Bertrand competition foreign investment in R&amp;D has a negative (indirect) strategic effect on foreign firms'