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

(gtxtreme123) #1
Creating and registering a dynamic receiver

Any IntentFilter you can express in XML can also be expressed in code this way. Just call
addCategory(String), addAction(String), addDataPath(String), and so on to configure your filter.


When you use dynamically registered broadcast receivers, you must also take care to
clean them up. Typically, if you register a receiver in a startup lifecycle method, you call
Context.unregisterReceiver(BroadcastReceiver) in the corresponding shutdown method.
Here, you register inside onStart() and unregister inside onStop(). If instead you registered inside
onCreate(...), you would unregister inside onDestroy().


(Be careful with onCreate(...) and onDestroy() in retained fragments, by the way. getActivity()
will return different values in onCreate(...) and onDestroy() if the screen has rotated. If you
want to register/unregister in Fragment.onCreate(Bundle) and Fragment.onDestroy(), use
getActivity().getApplicationContext() instead.)


Next, modify PhotoGalleryFragment to be a subclass of your new VisibleFragment.


Listing 29.8  Making your fragment visible (PhotoGalleryFragment.java)


public class PhotoGalleryFragment extends Fragment VisibleFragment {
...
}


Run PhotoGallery and toggle background polling a couple of times. You will see a nice toast pop up
(Figure 29.4).


Figure 29.4  Proof that your broadcast exists

Free download pdf