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 process by using custom permissions. You may find yourself asking, “Why am I using a global mechanism if I am just communicating with 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)). This will not work for PhotoGallery because you need to force NotificationReceiver to run last in the chain.

Second, sendBroadcastSync(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 PollWorker.doWork()) 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 or, in our experience, intuitive. For example, if you call sendBroadcastSync(…) from a background thread, all pending broadcasts will get flushed out on that background thread, even if 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
44.202.90.91