Chapter 29 Broadcast Intents
Creating and registering a dynamic receiver
Next, you need a receiver for your ACTION_SHOW_NOTIFICATION broadcast intent.
You could write a standalone broadcast receiver, like StartupReceiver, and register it in the manifest.
But that would not be ideal in this case. Here, you want PhotoGalleryFragment to receive the intent
only while it is alive. A standalone receiver declared in the manifest would always receive the intent
and would need some other way of knowing that PhotoGalleryFragment is alive (which is not easily
achieved in Android).
The solution is to use a dynamic broadcast receiver. A dynamic receiver is registered in code, not
in the manifest. You register the receiver by calling registerReceiver(BroadcastReceiver,
IntentFilter) and unregister it by calling unregisterReceiver(BroadcastReceiver). The receiver
itself is typically defined as an inner instance, like a button-click listener. However, since you need the
same instance in registerReceiver(...) and unregisterReceiver(BroadcastReceiver), you will
need to assign the receiver to an instance variable.
Create a new abstract class called VisibleFragment, with Fragment as its superclass. This class will
be a generic fragment that hides foreground notifications. (You will write another fragment like this in
Chapter 30.)
Listing 29.7 A receiver of VisibleFragment’s own (VisibleFragment.java)
public abstract class VisibleFragment extends Fragment {
private static final String TAG = "VisibleFragment";
@Override
public void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(PollService.ACTION_SHOW_NOTIFICATION);
getActivity().registerReceiver(mOnShowNotification, filter);
}
@Override
public void onStop() {
super.onStop();
getActivity().unregisterReceiver(mOnShowNotification);
}
private BroadcastReceiver mOnShowNotification = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getActivity(),
"Got a broadcast:" + intent.getAction(),
Toast.LENGTH_LONG)
.show();
}
};
}
Note that to pass in an IntentFilter, you have to create one in code. Your IntentFilter here is
identical to the filter specified by the following XML: