Chapter 29 Broadcast Intents
For the More Curious: Detecting the Visibility of Your Fragment
When you reflect on your PhotoGallery implementation, you may notice that you used the global
broadcast mechanism to broadcast the SHOW_NOTIFICATION intent. However, you locked the receiving
of that broadcast to items local to your app progress by using custom permissions. You may find
yourself asking, “Why am I using a global mechanism if I am just communicating things in my own
app? Why not a local mechanism instead?”
This is because you were specifically trying to solve the problem of knowing whether
PhotoGalleryFragment was visible. The combination of ordered broadcasts, standalone receivers,
and dynamically registered receivers you implemented gets the job done. There is not a more
straightforward way to do this in Android.
More specifically, LocalBroadcastManager would not work for PhotoGallery’s notification broadcast
and visible fragment detection, for two main reasons.
First, LocalBroadcastManager does not support ordered broadcasts (though it does provide a blocking
way to broadcast, namely sendBroadcastSync(Intent intent)). This will not work for PhotoGallery
because you need to force NotificationReceiver to run last in the chain.
Second, sendBroadcastSync(Intent intent) does not support sending and receiving a broadcast
on separate threads. In PhotoGallery you need to send the broadcast from a background thread (in
PollService.onHandleIntent(...)) and receive the intent on the main thread (by the dynamic receiver
that is registered by PhotoGalleryFragment on the main thread in onStart(...)).
As of this writing, the semantics of LocalBroadcastManager’s thread delivery are not well documented
and, in our experience, are not intuitive. For example, if you call sendBroadcastSync(...) from a
background thread, all pending broadcasts will get flushed out on that background thread regardless of
whether they were posted from the main thread.
This is not to say LocalBroadcastManager is not useful. It is simply not the right tool for the problems
you solved in this chapter.