You say Intent I say Intent

The Intent class is used in similar sounding but very different scenarios.

There are Intents used to assist in navigation from one activity to the next, such as the example given earlier of VIEWing a contact record. Activities are the targets of these kinds of Intents used with the startActivity or startActivityForResult methods.

Services can be started by passing an Intent to the startService method.

BroadcastReceivers receive Intents when responding to systemwide events such as the phone ringing or an incoming text message.

The Activity represents a very visible application component within Android. With assistance from the View class covered in chapter 3, the Activity is the most common type of Android application. The next topic of interest is the Service, which runs in the background and does not generally present a direct UI. SERVICE

If an application is to have a long lifecycle, it should be put into a Service. For example, a background data synchronization utility running continuously should be implemented as a Service.

Like the Activity, a Service is a class provided in the Android runtime that should be extended, as seen in listing 1.2, which sends a message to the Android log periodically.

Listing 1.2 A simple example of an Android Service package com.msi.manning.chapter1;

import android, app . Service; <—Q Service import import android.os.IBinder;

import android.util .Log; <1—Q Log import public class service1 extends Service implements Runnable { public static final String tag = "service1"; private int counter = 0;

@Override © Initialization in the protected void onCreate () { <1—

super.onCreate(); Thread aThread = new Thread (this); aThread.start();

Extending the Service class onCreate method public void run() {

Log.i(tag,"service1 firing : # " + counter++); Thread.sleep (10000); } catch(Exception ee) { Log.e(tag,ee.getMessage());

@Override public IBinder onBind(Intent intent) { <1—Q Binding to the Service return null; }

This example requires that the package O be imported. This package contains the Service class. This example also demonstrates Android's logging mechanism ©, which is useful for debugging purposes. Many of the examples in the book include using the logging facility. Logging is discussed in chapter 2. The service1 class G extends the Service class. This class also implements the Runnable interface to perform its main task on a separate thread. The onCreate O method of the Service class permits the application to perform initialization-type tasks. The onBind() method Q is discussed in further detail in chapter 4 when the topic of interprocess communication in general is explored.

Services are started with the startService(Intent) method of the abstract Context class. Note that, again, the Intent is used to initiate a desired result on the platform.

Now that the application has a UI in an Activity and a means to have a long-running task in a Service, it is time to explore the BroadcastReceiver, another form of Android application that is dedicated to processing Intents. BROADCASTRECEIVER

If an application wants to receive and respond to a global event, such as the phone ringing or an incoming text message, it must register as a BroadcastReceiver. An application registers to receive Intents in either of two manners:

■ The application may implement a <receiver> element in the AndroidMan-fest.xml file, which describes the BroadcastReceiver's class name and enumerates its IntentFilters. Remember, the IntentFilter is a descriptor of the Intent an application wants to process. If the receiver is registered in the AndroidManifest.xml file, it does not have to be running in order to be triggered. When the event occurs, the application is started automatically upon notification of the triggering event. All of this housekeeping is managed by the Android OS itself.

■ An application may register at runtime via the Context class's registerRe-ceiver method.

Like Services, BroadcastReceivers do not have a UI. Of even more importance, the code running in the onReceive method of a BroadcastReceiver should make no assumptions about persistence or long-running operations. If the BroadcastReceiver requires more than a trivial amount of code execution, it is recommended that the code initiate a request to a Service to complete the requested functionality.

NOTE The familiar Intent class is used in the triggering of BroadcastReceivers; the use of these Intents is mutually exclusive from the Intents used to start an Activity or a Service, as previously discussed.

A BroadcastReceiver implements the abstract method onReceive to process incoming Intents. The arguments to the method are a Context and an Intent. The method returns void, but a handful of methods are useful for passing back results, including setResult, which passes back to the invoker an integer return code, a String return value, and a Bundle value, which can contain any number of objects.

Listing 1.3 is an example of a BroadcastReceiver triggering upon an incoming text message.

Listing 1.3 A sample IntentReceiver package com.msi.manning.unlockingandroid;

import android.content.Context; import android.content.Intent; import android.content.IntentReceiver;

import android.util. Log; ^^ Extending public class MySMSMailBox extends BroadcastReceiver { <-' BroadcastReceiver public static final String tag = "MySMSMailBox";

Tag used in logging

@Override public void onReceive(Context context, Intent intent) { <-1 „ . . .

G onReceive method


if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) { <-Log.1(tag,"Found our Event!"); <-1

} | Write Check Intent's

Looking at listing 1.3 we find a few items to discuss. The class MySMSMailBox extends the BroadcastReceiver class O. This subclass approach is the most straightforward way to employ a BroadcastReceiver. Note the class name MySMSMailBox, as it will be used in the AndroidManifest.xml file, shown in listing 1.4. The tag variable C is used in conjunction with the logging mechanism to assist in labeling messages sent to the console log on the emulator. Using a tag in the log enables filtering and organizing log messages in the console. Chapter 2 discusses the log mechanism in further detail. The onReceive method G is where all of the work takes place in a BroadcastReceiver—this method must be implemented. Note that a given BroadcastReceiver can register multiple IntentFilters and can therefore be instantiated for an arbitrary number of Intents.

It is important to make sure to handle the appropriate Intent by checking the action of the incoming Intent, as shown in O. Once the desired Intent is received, carry out the specific functionality required. A common task in an SMS-receiving application would be to parse the message and display it to the user via a Notification Manager display. In this snippet, we simply record the action to the log Q.

In order for this BroadcastReceiver to fire and receive this Intent, it must be listed in the AndroidManifest.xml file, as shown in listing 1.4. This listing contains the elements required to respond to an incoming text message.

Listing 1.4 AndroidManifest.xml

<?xml version= "1.0" encoding= "utf- 8 " ? > teqmred permission Q

<manifest xmlns:android="" package="com.msi.manning.unlockingandroid">

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

<application android:icon="@drawable/icon" > <activity android:name=".chapter1" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter>

</activity> C Receiver tag; Q totentfHtei-

<receiver android:name=" .MySMSMailBox" > <—-J note the "•" definition

<action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver> </application> </manifest>

Certain tasks within the Android platform require the application to have a designated privilege. To give an application the required permissions, the <uses-permission> tag is used Q. This is discussed in detail later in this chapter in the AndroidManifest.xml section. The <receiver> tag contains the class name of the class implementing the BroadcastReceiver. In this example the class name is MySMSMailBox, from the package com.msi.manning.unlockingandroid. Be sure to note the dot that precedes the name Q. The dot is required. If your application is not behaving as expected, one of the first places to check is your Android.xml file, and look for the dot! The IntentFilter is defined in the <intent-filter> tag. The desired action in this example is android.provider.Telephony.SMS_RECEIVED ©. The Android SDK enumerates the available actions for the standard Intents. In addition, remember that user applications can define their own Intents as well as listen for them.

Now that we have introduced Intents and the Android classes that process or handle Intents, it's time to explore the next major Android application topic, the ContentProvider, Android's preferred data-publishing mechanism. CONTENT PROVIDER

If an application manages data and needs to expose that data to other applications running in the Android environment, a ContentProvider should be implemented. Alternatively, if an application component (Activity, Service, or Broadcast-Receiver) needs to access data from another application, the other application's

0 0

Post a comment