在片段中注册和注销 BroadcastReceiver [英] Registering and unregistering BroadcastReceiver in a fragment

查看:24
本文介绍了在片段中注册和注销 BroadcastReceiver的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用有一个带有 3 个片段选项卡的操作栏.在第二个片段中,我注册和取消注册 BroadcastReceiver.我在 onPause 中取消注册接收器并在 onCreateViewonResume 中注册它.

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));

getActivity().unregisterReceiver(batteryInfoReceiver);

1) 注册同一个接收器两次(在 onCreateView 和 onResume 中)可以吗?(是否无害?)

2) 仅在 onResume 中注册接收者就足够了吗?

推荐答案

查看生命周期Fragments 的一个>:

Have a look at life-cycle of Fragments:

onCreateView():当片段第一次绘制其用户界面时,系统会调用它.要为片段绘制 UI,必须从此方法返回一个视图,该视图是片段布局的根.如果片段不提供 UI,您可以返回 null.

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():该片段在正在运行的活动中可见

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

onPause():这通常是您应该提交任何应该在当前用户会话之后保留的更改的地方(因为用户可能不会回来).

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).

结论:

所以最好只在onResume()内注册接收器,在onPause()内取消注册,因为onCreateView() 仅处理视图层次结构.它与接收器无关.所以它无害但肯定没用.

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.

希望能帮到你!!

这篇关于在片段中注册和注销 BroadcastReceiver的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆