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

(gtxtreme123) #1
Passing and receiving data with ordered broadcasts

Right now you are sending your own personal private broadcast, but so far you only have one-way
communication (Figure 29.5).


Figure 29.5  Regular broadcast intents


This is because a regular broadcast intent is conceptually received by everyone at the same time. In
reality, because onReceive(...) is called on the main thread, your receivers are not actually executed
concurrently. However, it is not possible to rely on their being executed in any particular order or to
know when they have all completed execution. As a result, it is a hassle for the broadcast receivers to
communicate with each other or for the sender of the intent to receive information from the receivers.


You can implement two-way communication using an ordered broadcast intent (Figure 29.6). Ordered
broadcasts allow a sequence of broadcast receivers to process a broadcast intent in order. They also
allow the sender of a broadcast to receive results from the broadcast’s recipients by passing in a special
broadcast receiver, called the result receiver.


Figure 29.6  Ordered broadcast intents


On the receiving side, this looks mostly the same as a regular broadcast. But you get an additional
tool: a set of methods used to change the return value of your receiver. Here, you want to cancel
the notification. This can be communicated by use of a simple integer result code. You will use the
setResultCode(int) method to set the result code to Activity.RESULT_CANCELED.

Free download pdf