Reputation: 10346
I have an activity with two fragments, with only 1 of the two fragments being displayed at a given time, as determined by the user. Both fragments subscribe to data via a broadcast receiver.
The acitivty manages which fragment is displayed using the fragment manager's replace() method, e.g.
getFragmentManager().beginTransaction().replace(R.id.north_fragment, fragment1, FRAGMENT_TAG).commit();
The Broadcast Receivers are registered in the Fragment's onCreateView() override: The broadcast receiver receives the appropriate data as expected.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_spectrum_analyzer_graph, container, false);
setupGraphView(rootView);
// register for Spectrum Frame Response messages
myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive()");
// do stuff
}
}
The broadcast receiver is unregistered in onDestroyView(), e.g.:
@Override
public void onDestroyView() {
super.onDestroyView();
getActivity().unregisterReceiver(m_spectrumDataFrameReceiver);
}
Is there a way I can keep the fragment receiving data through the BroadcastReceiver, even when it's not visible (after it's been destroyed)? I want the receiver to continue getting data and storing it in the Fragment, even if the fragment is not visible (but the activity is visible), but I know that I need to unregister the broadcast receiver at some point.
Should unregistration be done when the Activity is destroyed (calling in to its activities to unregister), or is it too late here? I'm fairly new to the intricacies of Fragment lifecyle, and am not quite sure what to do.
Upvotes: 2
Views: 1388
Reputation: 8034
You should register your receiver in activity onResume and unregister it in onPause. You receiver will receive broadcast as long as activity is running. Then you can pass received data to respective fragment by any means.
Upvotes: 1
Reputation: 26198
Instead of replacing
each fragment everytime just use the add
method fragment transaction so it is still alive when invisible.
solution:
replace the replace
use the add
beginTransaction().add(R.id.north_fragment, fragment1, FRAGMENT_TAG).commit();
Upvotes: 1