gpt4 book ai didi

android - 在 onCreate/onDestroy 上注册/注销 BroadcastReceivers

转载 作者:行者123 更新时间:2023-11-29 17:49:41 25 4
gpt4 key购买 nike

我在一些 Activity 中使用本地 BroadcastReceivers 来处理通过 LocalBroadcastManager 发送的广播。我看到许多建议(例如 here)建议不要在 onCreate/onDestroy Activity 处理程序中注册/注销这些接收器。

我不太明白为什么。 “官方”的解释是 onDestory 不能保证每次 Activity 被销毁时都会被调用:

"There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it..."

“终止托管进程”是否意味着对整个 Activity 的资源进行全面清理?此清理不包括本地注册的接收器吗?为什么这个建议不适用于其他本地定义的对象?为什么保证它们会被清理而 BroadcastReceivers 不会?

感谢您的知识渊博的建议。

最佳答案

I don't quite understand why.

Activity 中 LocalBroadcastManager 的常见用法仅需要在 Activity 处于前台时接收广播。因此,onResume()/onPause() 是这些场景的正确选择。

如果你觉得在onCreate()/onDestroy()中注册/注销是你想要做的,并且这样做不会伤害用户(例如,浪费 CPU 时间处理不相关的事件),欢迎您这样做。

Doesn't "killing the hosting process" means that there is an overall cleanup of the entire activities' resources ?

是的,确实如此。

Doesnt this cleanup include locally registered receivers ?

是的,确实如此。

How come this recommendation doesnt apply to other locally defined objects ?

确实如此。

关于android - 在 onCreate/onDestroy 上注册/注销 BroadcastReceivers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23846352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com