Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

android - Registering and unregistering BroadcastReceiver in a fragment

My app has an action bar with 3 fragment tabs. In the second fragment I register and unregister a BroadcastReceiver. I unregister the receiver in onPause and register it in onCreateView and in onResume.

getActivity().registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

and

getActivity().unregisterReceiver(batteryInfoReceiver);

1) Is it all right to register the same reciever twice (in onCreateView and onResume)?(is it harmless?)

2) Is it enough to just register the reciever in onResume?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Have a look at life-cycle of Fragments:

onCreateView(): The system calls this when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.

onResume(): The fragment is visible in the running activity

onPause(): This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).

Conclusion:

So it is better to register the receiver only inside onResume() and unregister inside onPause() because onCreateView() deals with view hierarchy only. It has nothing to do with receiver. So it is not harmful but surely it is useless.

I hope it will be helpful!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...