Registering and unregistering BroadcastReceiver in a fragment

前端 未结 3 1455
旧巷少年郎
旧巷少年郎 2020-12-02 12:00

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 re

3条回答
  •  执念已碎
    2020-12-02 12:38

    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!!

提交回复
热议问题