css216 mobile programming android, chapter 13 book: “professional android™ 2 application...

30
CSS216 MOBILE PROGRAMMING Android, Chapter 13 Book: “Professional Android™ 2 Application Development” by Reto Meier, 2010 by: Andrey Bogdanchikov ( [email protected] )

Upload: jessie-moody

Post on 27-Dec-2015

220 views

Category:

Documents


0 download

TRANSCRIPT

CSS216 MOBILE PROGRAMMING

Android, Chapter 13

Book: “Professional Android™ 2 Application Development” by Reto Meier, 2010

by: Andrey Bogdanchikov ( [email protected] )

Outline - Telephony and SMS

• Initiating phone calls• Reading the phone, network, data connectivity, and SIM states

• Monitoring changes to the phone, network, data connectivity, and SIM states

• Using Intents to send SMS and MMS messages• Using the SMS Manager to send SMS Messages• Handling incoming SMS messages

Introduction• In this chapter, you’ll learn to use Android’s telephony APIs to

monitor mobile voice and data connections as well as incoming and outgoing calls, and to send and receive SMS (short messaging service) messages.

• You’ll take a look at the communication hardware by examining the telephony package for monitoring phone state and phone calls, as well as initiating calls and monitoring incoming call details.

• Android also offers full access to SMS functionality, letting you send and receive SMS messages from within your applications. Using the Android APIs, you can create your own SMS client application to replace the native clients available as part of the software stack.

Telephony• The Android telephony APIs let your applications access the

underlying telephone hardware stack, making it possible to create your own dialer — or integrate call handling and phone state monitoring into your applications.

• Because of security concerns, the current Android SDK does not allow you to create your own ‘‘in call’’ Activity — the screen that is displayed when an incoming call is received or an outgoing call has been placed.

• The following sections focus on how to monitor and control phone, service, and cell events in your applications to augment and manage the native phone-handling functionality. If you wish, you can use the same techniques to implement a replacement dialer application.

Launching the Dialer to Initiate Phone Calls

• Best practice is to use Intents to launch a dialer application to initiate new phone calls. Use an Intent action to start a dialer activity; you should specify the number to dial using the tel: schema as the data component of the Intent.

• Use the Intent.ACTION_DIAL Activity action to launch a dialer rather than dial the number immediately.

• This action starts a dialer Activity, passing in the specified number but allowing the dialer application to manage the call initialization (the default dialer asks the user to explicitly initiate the call).

• This action doesn’t require any permissions and is the standard way applications should initiate calls.

Managing Bluetooth Properties and State

• The Bluetooth Adapter offers methods for reading and setting properties of the local Bluetooth hardware.

• The Bluetooth Adapter properties can be read and changed only if the Bluetooth adapter is currently turned on (that is, if its device state is enabled). If the device is off, these methods will return null.

• If the Bluetooth Adapter is turned on, and you have included the BLUETOOTH permission in your manifest, you can access the Bluetooth Adapter’s friendly name (an arbitrary string that users can set and then use to identify a particular device) and hardware address.

Dialing a numberIntent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:1234567"));

startActivity(intent);• By using an Intent to announce your intention to dial a

number, your application can remain decoupled from the dialer implementation used to initiate the call.

• For example, if you were to replace the existing dialer with a hybrid that allows IP-based telephony, using Intents to dial a number from your other applications would let you leverage this new dialer functionality.

Replacing the Native Dialer• Replacing the native dialer application involves two steps:• 1. Intercepting Intents that are currently serviced by

the native dialer.• 2. Initiating, and optionally managing, outgoing calls.

• The native dialer application currently responds to Intent actions corresponding to a user’s pressing the hardware call button, asking to view data using the tel: schema, or making a request to dial a number using the tel: schema.

Filters• To intercept these requests include <intent-filter> tags on your

new Activity that listens for the following actions:• ➤ Intent.ACTION_CALL_BUTTON This action is broadcast

when the device’s hardware call button is pressed. Create an Intent Filter listening for this action as a default action.

• ➤ Intent.ACTION_DIAL The Intent action described in the previous section, this Intent is used by applications which want to launch the dialer to make a phone call. The Intent Filter used to capture this action should be both default and browsable (to support dial requests from the browser), and must specify the tel: schema to replace existing dialer functionality (though it can support additional schemes).

• ➤ Intent.ACTION_VIEW The view action is used by applications wanting to view a piece of data. Ensure that the Intent Filter specifies the tel: schema to allow your new Activity to be used to view telephone numbers.

Accessing Phone and Network Properties and Status• Access to the telephony APIs is managed by the Telephony

Manager, accessible using the getSystemService method as shown here…

String srvcName = Context.TELEPHONY_SERVICE;TelephonyManager telephonyManager = (TelephonyManager)getSystemService(srvcName);

• The Telephony Manager provides direct access to many of the phone properties, including device, network, SIM, and data state details.

Reading SIM Details• If your application is running on a GSM device it will have

a SIM. You can query the SIM details from the Telephony Manager to obtain the ISO country code, operator name, and operator MCC (mobile country code) and MNC (mobile network code) for the SIM installed in the current device.

• These details can be useful if you need to provide specialized functionality for a particular carrier.

• You can also obtain the serial number for the current SIM if you include the READ_PHONE_STATE uses-permission in your application manifest.

Reading SIM detailsint simState = telephonyManager.getSimState();

switch (simState) {case (TelephonyManager.SIM_STATE_ABSENT): break;

case (TelephonyManager.SIM_STATE_NETWORK_LOCKED): break;

case (TelephonyManager.SIM_STATE_PIN_REQUIRED): break;

case (TelephonyManager.SIM_STATE_PUK_REQUIRED): break;

case (TelephonyManager.SIM_STATE_UNKNOWN): break;

case (TelephonyManager.SIM_STATE_READY): {// Get the SIM country ISO code

String simCountry = telephonyManager.getSimCountryIso();

// Get the operator code of the active SIM (MCC + MNC)

String simOperatorCode = telephonyManager.getSimOperator();

// Get the name of the SIM operator

String simOperatorName = telephonyManager.getSimOperatorName();

// -- Requires READ_PHONE_STATE uses-permission --

// Get the SIM’s serial number

String simSerial = telephonyManager.getSimSerialNumber();

break;

}default: break;}

Monitoring Incoming Phone Calls• One of the most popular reasons for monitoring phone state is to detect,

and react to, incoming phone calls.• To do so, override the onCallStateChanged method in a Phone State

Listener implementation, and register it as shown in here to receive notifications when the call state changes.

PhoneStateListener callStateListener = new PhoneStateListener() {public void onCallStateChanged(int state, String incomingNumber)

{// TODO React to incoming call.} };telephonyManager.listen(callStateListener,

PhoneStateListener.LISTEN_CALL_STATE);• The onCallStateChanged handler receives the phone number associated

with incoming calls, and the state parameter represents the current call state as one of the following three values:• ➤ TelephonyManager.CALL_STATE_IDLE When the phone is neither ringing nor in a

call• ➤ TelephonyManager.CALL_STATE_RINGING When the phone is ringing• ➤ TelephonyManager.CALL_STATE_OFFHOOK When the phone is currently in a call

Introducing SMS and MMS• SMS technology is designed to send short text messages

between mobile phones. It provides support for sending both text messages (designed to be read by people) and data messages (meant to be consumed by applications). More recently MMS (multimedia messaging service) messages have allowed users to send and receive messages that include multimedia attachments such as photos, videos, and audio.

• Because SMS and MMS are mature mobile technologies, there’s a lot of information out there that describes the technical details of how an SMS or MMS message is constructed and transmitted over the air. Rather than rehash that information here, the following sections focus on the practicalities of sending and receiving text, data, and multimedia messages from within Android applications.

Using SMS and MMS in Your Application

• Android provides full SMS functionality from within your applications through the SMSManager. Using the SMS Manager, you can replace the native SMS application to send text messages, react to incoming texts, or use SMS as a data transport layer.

• At this time, the Android API does not include simple support for creating MMS messages from within your applications, though you can use the SEND and SEND_TO actions in Intents to send both SMS and MMS messages using a messaging application installed on the device.

Sending an SMS message using IntentsIntent smsIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("sms:55512345"));

smsIntent.putExtra("sms_body", "Press send to send me");

startActivity(smsIntent);• You can also attach files (effectively creating an MMS

message) to your messages. Add an Intent.EXTRA_STREAM with the URI of the resource to attach, and set the Intent type to the mime-type of the attached resource.

• Note that the native MMS application doesn’t include an Intent Receiver for ACTION_SENDTO with a type set. Instead, you will need to use ACTION_SEND and include the target phone number as an address extra.

Sending an MMS message with an attached image

// Get the URI of a piece of media to attach.

Uri attached_Uri = Uri.parse("content://media/external/images/media/1");

// Create a new MMS intent

Intent mmsIntent = new Intent(Intent.ACTION_SEND, attached_Uri);

mmsIntent.putExtra("sms_body", "Please see the attached image");

mmsIntent.putExtra("address", "07912355432");

mmsIntent.putExtra(Intent.EXTRA_STREAM, attached_Uri);

mmsIntent.setType("image/png");

startActivity(mmsIntent);

Listening for Incoming SMS Messages

• When a new SMS message is received by the device, a new broadcast Intent is fired with the android.provider.Telephony.SMS_RECEIVED action. Note that this is a string literal, the SDK currently doesn’t include a reference to this string, so you must specify it explicitly when using it in your applications.

• The SMS received action string is hidden (therefore unsupported). As such it is subject to change at any future platform release. As always, be very cautious when using unsupported platform features as they are subject to change in future platform releases.

Incoming SMS• For an application to listen for SMS Intent broadcasts, it needs to

specify the RECEIVE_SMS manifest permission. Request this permission by adding a <uses-permission> tag to the application manifest, as shown in the following snippet:

<uses-permission android:name="android.permission.RECEIVE_SMS” />

Listening for incoming SMS messages:

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

}

Chapter 14 - Sensors• Using the Sensor Manager• The available sensor-types• Monitoring sensors and interpreting sensor values

• Using the compass, accelerometer, and orientation sensors

• Remapping your orientation reference frame• Controlling device vibration

Introduction• Modern mobile phones are much more than simple

communications devices with a connection to the Internet. With microphones, cameras, accelerometers, compasses, temperature gauges, and brightness detectors, smartphones have become extra-sensory devices, able to augment your own perceptions.

• Later chapters will explore use of the camera and microphone; in this chapter you will explore the environmental sensors potentially available on Android devices. Sensors that detect physical and environmental properties offer an exciting innovation for enhancing the user experience of mobile applications.

• The incorporation of electronic compasses, gravity sensors, brightness gauges, and proximity sensors in modern devices provides an array of new possibilities for interacting with devices, such as augmented reality and physical movement-based input.

Using sensors and the sensor manager

• The Sensor Manager is used to manage the sensor hardware available on Android devices. Use getSystemService to return a reference to the Sensor Manager Service, as shown in the following snippet:

String service_name = Context.SENSOR_SERVICE;SensorManager sensorManager = (SensorManager)getSystemService(service_name);

Introducing Sensors• Like location-based Services, Android abstracts the sensor

implementations of each device. The Sensor class is used to describe the properties of each hardware sensor, including its type, name, manufacturer, and details on its accuracy and range.

• The Sensor class includes a set of constants used to describe what type of hardware sensor is being represented by a Sensor object. These constants take the form of Sensor.TYPE_<TYPE>.

• The following section describes each supported sensor-type, after which you’ll learn how to find and use those sensors.

Supported Android Sensors ➤ Sensor.TYPE_ACCELEROMETER A three-axis accelerometer sensor that returns the current acceleration along three axes in m/s2.

➤ Sensor.TYPE_GYROSCOPE A gyroscopic sensor that returns the current device orientation on three axes in degrees.

➤ Sensor.TYPE_LIGHT An ambient light sensor that returns a single value describing the ambient illumination in lux. A light sensor is commonly used to dynamically control the screen brightness.

➤ Sensor.TYPE_MAGNETIC_FIELD A magnetic field sensor that finds the current magnetic field in microteslas along three axes.

➤ Sensor.TYPE_ORIENTATION An orientation sensor that returns the device orientation on three axes in degrees.

➤ Sensor.TYPE_PRESSURE A pressure sensor that returns a single value, the current pressure exerted on the device in kilopascals.

➤ Sensor.TYPE_PROXIMITY A proximity sensor that indicates the distance between the device and the target object in meters. How a target object is selected, and the distances supported, will depend on the hardware implementation of the proximity detector. A typical use for the proximity sensor is to detect when the device is being held up against the user’s ear and to automatically adjust screen brightness or initiate a voice command.

➤ Sensor.TYPE_TEMPERATURE A thermometer that returns temperature in degrees Celsius.

Finding Sensors• An Android device can include multiple implementations of a particular sensor-

type. To find the default Sensor implementation for a particular type use the Sensor Manager’s getDefaultSensor method, passing in the sensor-type required from the constants described in the previous section.

• The following snippet returns the default gyroscope. If no default Sensor exists for the given type, the method returns null.

Sensor defaultGyroscope = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);

• Alternatively, use getSensorList to return a list of all the available Sensors of a given type, as shown in the following code, which returns all the available pressure sensor objects:

List<Sensor> pressureSensors = sensorManager.getSensorList(Sensor.TYPE_PRESSURE);

• To find every Sensor available on the host platform use getSensorList, passing in Sensor.TYPE_ALL, as shown here:

List<Sensor> allSensors = sensorManager.getSensorList(Sensor.TYPE_ALL);

• This technique lets you determine which Sensors, and sensor-types, are available on the host platform

Using the Compass, Accelerometer, and Orientation Sensors

• Using movement and orientation within applications is possible thanks to the inclusion of orientation and accelerometer sensors in many modern devices.

• In recent years these sensors have become increasingly common, having found their way into game controllers like the Nintendo Wii and mobile smartphone handsets like the Apple iPhone, Palm Pre, and many Android devices.

• Accelerometers and compasses are used to provide functionality based on device direction, orientation, and movement. A recent trend is to use this functionality to provide input mechanisms other than the traditional touchscreen, trackball, and keyboard.

What we have• The availability of compass and accelerometer Sensors depends on the hardware on which your application runs. When available, they are exposed through the Sensor Manager, allowing you to do the following:• Determine the current device orientation• Monitor and track changes in orientation• Know which direction the user is facing• Monitor acceleration—changes in movement rate—in any

direction: vertically, laterally, or longitudinally

What we can do• This opens some intriguing possibilities for your applications.

By monitoring orientation, direction, and movement, you can:• ➤ Use the compass and accelerometer to determine your speed and

direction. Use these with a map, camera, and location-based services to create augmented reality interfaces that overlay location-based data over the real-time camera feed.

• ➤ Create user interfaces that adjust dynamically to suit the orientation of your device. Android already alters the native screen orientation when the device is rotated from portrait to landscape or vice versa.

• ➤ Monitor for rapid acceleration to detect if a device has been dropped or thrown.

• ➤ Measure movement or vibration. For example you could create an application that lets you lock your device; if any movement is detected while it’s locked it could send an alert SMS that includes the current location.

• ➤ Create user interface controls that use physical gestures and movement as input.

Summary• All these Sensors can make your application shine up. • So it is very cool to add some functionality that uses

Sensors in their work.• The real implementation and use of this technology is up

to your self-study abilities

THE ENDThank you