Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 29  Broadcast Intents


Activities and services should respond to implicit intents whenever they are used as part of a public
API. When they are not part of a public API, explicit intents are almost always sufficient. Broadcast
intents, on the other hand, only exist to send information to more than one listener. So while broadcast
receivers can respond to explicit intents, they are rarely, if ever, used this way, because explicit intents
can only have one receiver.


Receiving a System Broadcast: Waking Up on Boot


PhotoGallery’s background alarm works, but it is not perfect. If the user reboots the device, the alarm
will be forgotten.


Apps that perform an ongoing process for the user generally need to wake themselves up after the
device is booted. You can detect when boot is completed by listening for a broadcast intent with the
BOOT_COMPLETED action. The system sends out a BOOT_COMPLETED broadcast intent whenever the device
is turned on. You can listen for it by creating and registering a standalone broadcast receiver that filters
for the appropriate action.


Creating and registering a standalone receiver


A standalone receiver is a broadcast receiver that is declared in the manifest. Such a receiver can be
activated even if your app process is dead. (Later you will learn about dynamic receivers, which can
instead be tied to the lifecycle of a visible app component, like a fragment or activity.)


Just like services and activities, broadcast receivers must be registered with the system to do anything
useful. If the receiver is not registered with the system, the system will not send any intents its way
and, in turn, the receiver’s onReceive(...) will not get executed as desired.


Before you can register your broadcast receiver, you have to write it. Create a new Java class called
StartupReceiver that is a subclass of android.content.BroadcastReceiver.


Listing 29.1  Your first broadcast receiver (StartupReceiver.java)


public class StartupReceiver extends BroadcastReceiver{
private static final String TAG = "StartupReceiver";


@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Received broadcast intent: " + intent.getAction());
}
}


A broadcast receiver is a component that receives intents, just like a service or an activity. When an
intent is issued to StartupReceiver, its onReceive(...) method will be called.

Free download pdf