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

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

问题描述

我的应用程序有3个片段标签的操作栏。 在第二个片段我注册和注销一个BroadcastReceiver。 我注销接收器的onPause onCreateView 注册并在 onResume

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)它是注册相同reciever两次(在onCreateView和onResume好吗)?(是无害的?)

2),它是不够的,只是注册reciever在onResume?

推荐答案

看一看生命周期 片段的:

onCreateView(): 系统调用这个时,它的时间段来绘制其用户界面的第一次。要绘制您片段的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天全站免登陆