In this chapter will learn about Android Broadcast Receivers. We already had a small introduction with this guy but today we shall know a little more than what we have known about him.
Android Broadcast Receiver is one of the principal components of Android application development. Broadcast receiver which is also known as receiver is a component of android application. With this component we can register receivers for any system-level or application-level event. Once that event occurs, android system will notify the registered receivers about the execution of events respectively.
3.10.1 Types of Broadcasts
There are two types of broadcasts received by receivers and they are:
1. Normal Broadcasts:
- These are asynchronous broadcasts.
- Receivers of this type of broadcasts may run in any order, sometimes altogether.
- This is efficient.
- Receivers cannot use the result.
- They cannot abort the included APIs.
- These broadcasts are sent with Context.sendBroadcast
2. Ordered Broadcasts
- These are synchronous broadcasts.
- One broadcast is delivered to one receiver at a time.
- Receivers can use the result. In fact as each receiver executes, result is passed to next receiver.
- Receiver can abort the broadcast and hence no broadcast is received by other receivers.
- The order of receivers is managed and controlled by the attribute android:priority in corresponding intent-filter.
- If receivers will have same priority then they may run in any order.
3.10.2 Registering Broadcasts
We use intent class to send and receive the broadcasts but they are not similar to starting activity with intents. Intents associated with activities are foreground processes whereas broadcast intents are background processes. In case of broadcast intents it is possible that even user may not be aware of what is going on in background. sendBroadcast() is the main method responsible for sending broadcasts.
If we don’t want our broadcasts to be global then we can use another class instead of sendBroadcast() method. This class is LocalBroadccastManager. There will be no inter-process communication and hence no security issue. No other application will be able to know about this broadcasts except the intended application. We have to register our receiver. Registering a receiver can be done in following two ways:
- Static: Implementation is published through Manifest file. It has a <receiver/> tag which is meant for this purpose.
- Dynamic: It is registered dynamically by Context.registerReceiver().
If a receiver is registered in the onResume() callback of our Activity then it should be unregistered in the onPause() callback method. While you pause the activity, receivers will take rest and don’t do anything which in turn saves resources.
3.10.3 Receiver and Process Life cycle
Receiver has a limited and defined life cycle. Consider the following points about life cycle of receiver:
- BroadcastReceiver object is valid till the accomplishment of call onReceiver(Context, Intent).
- When function returns, system will grant it as an object which has finished its work. It is not active.
- In this case, NotificationManager API should be used.
- In case of asynchronous operations the scenario is different. There has to be something which should handle the asynchronous operation after it returns. In this case, BroadcastReceiver is killed by system before asynchronous operation completes.
- In this case, Context.startService() should be used to send command to service.
Processes associated with Broadcast receivers have the following life style:
- Current process executing Broadcast Receiver is a foreground process. It is not killed by system unless it is under immense scarcity of resources.
- In cases of processes hosting BroadcastReceivers, which are never used by user or the one which is recently not in use, is considered an empty process. And an empty process can be killed anytime.
- Once onReceive(Context, Intent) returns, broadcast receiver becomes inactive and hence it has no special priority over other application components.
3.10.4 System Broadcasts
There are many system level services which broadcast messages at system wide level which can be used. These are intents which signal changes. Some of the native actions are listed in the following table:
Serial Number | Action Name | Description |
1
| ACTION_BOOT_COMPLETED
| When device completes its start up sequence then this broadcast is fired. This broadcast is received only when the application has the RECEIVE_BOOT_COMPLETED permission. |
2 | ACTION_CAMERA_BUTTON | This broadcast is fired when camera is clicked |
3 | ACTION_DATE_CHANGED, ACTION_TIME_CHANGED | When date and/ or time are changed manually then these broadcasts are fired respectively. |
4 | ACTION_MEDIA_EJECT | Before external storage media is ejected, this broadcast is fired. To save and close any opened files which were read from or written to external storage media, application should listen to this broadcast. |
5 | ACTION_MEDIA_MOUNTED, ACTION_MEDIA_UNMOUNTED | When any external storage media is added and / or removed, these broadcasts are fired. |
6 | ACTION_NEW_OUTGOING_CALL | When a new outgoing call is placed this broadcast is fired |
7 | ACTION_SCREEN_ON, ACTION_SCREEN_OFF | When screen turns on and/or turns off, this broadcast is fired. |
8 | ACTION_TIMEZONE_CHANGED | Whenever device’s current time zone is changed this broadcast is fired. |
Table Native Broadcasts
3.10.5 Common Methods
Let us study some of the common methods and they are as follows:
1.abortBroadcast():
- This method doesn’t works with asynchronous broadcasts.
- It sets the flag which indicates that the present receiver should abort this broadcast.
- Other broadcast receivers will be prevented from receiving this broadcast.
- Syntax:
public final void abortBroadcast();
2.clearAbortBroadcast():
- The flag set by abortBroadcast() method is cleared by this function call.
- Syntax:
public final void clearAbortBroadcast();
3.getAbortBroadcast():
- This method returns the flag which signals broadcast receiver to abort the current broadcast or not.
- Syntax:
public final Boolean getAbortBroadcast();
- getDebugUnregister():
- This returns the previous value given to setDebugUnregister(boolean)
- Syntax:
public final Boolean getDebugUnregister();
5.getResultCode():
- Previous receiver sets a result code.
- This current result code is retrieved by this method.
- Result data is integer
- Syntax:
public final intgetResultCode();
6.getResultData():
- Previous receiver sets a result data.
- It may be null.
- Current result data I retrieved by this method.
- Result data is of type string
- Syntax:
public final String getResultData();
7.isInitialStickyBroadcast():
- If receiver is processing the initial value of a sticky broadcast then this method returns true.
- This has nothing to do with current broadcast.
- It is the value of last broadcast and is held in sticky cache.
- Syntax:
public final Boolean isInitialStickyBroadcast();
8.isOrderedBroadcast():
- When receiver processes a broadcast from ordered broadcast, this method returns true.
- Syntax;
public final Boolean isOrderedBroadcast();
9.onReceive(Context,Intent):
- When broadcast receiver receives some kind of broadcast intent then this method is called.
- Current results can be viewed or modified using other methods when this method was in use.
- By default, this method is associated with the main thread of application.
- If <receiver/> tag is used then as soon as function returns the object is killed.
- Context is in which the receiver is running
- Intent which is intended to be received.
- Syntax:
public abstract void onReceive(Context context, Intent intent);
10.setOrderedHint(boolean):
- This hints whether broadcast receiver is running on ordered mode or not.
- Syntax:
public final void setOrederedHint(Boolean isOrdered);