简体   繁体   English

Android BroadcastReceiver生命周期:动态注册接收器的文档错误?

[英]Android BroadcastReceiver Lifecycle: documentation wrong for dynamically registered receiver?

I define a BatteryInfo extends BroadcastReceiver class. 我定义了BatteryInfo extends BroadcastReceiver类。 I call its constructor once in my Activity onCreate() . 我在Activity onCreate()一次调用它的构造函数。 I register it with Activity.registerReceiver in my onCreate() . 我在我的onCreate()Activity.registerReceiver注册了它。

I am trying to figure out whether I need to unregister it and/or set its reference to null in order to allow my Activity to die without leaking memory or clogging up intent senders in the system, or whether the system gracefully tosses everything associated with this on its own. 我试图弄清楚是否需要注销它和/或将其引用设置为null才能使我的Activity死掉而不会泄漏内存或阻塞系统中的意图发送者,或者系统是否优雅地丢弃了与此相关的所有内容在其自己的。 Towards that end I am pondering the BroadcastReceiver Lifecycle where I read: 为此,我正在考虑我的BroadcastReceiver生命周期

A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). BroadcastReceiver对象仅在对onReceive(Context,Intent)的调用期间有效。 Once your code returns from this function, the system considers the object to be finished and no longer active." 一旦您的代码从该函数返回,系统就会认为该对象已完成并且不再处于活动状态。”

what does this mean? 这是什么意思? Obviously the object I have created with new BatteryInfo() and registered with registerReceiver() persists through the entire time my activity persists. 显然,对象我与创建new BatteryInfo()并与注册registerReceiver()通过我的活动依然存在,整个时间持续。 I log results from it and see them that entire time. 我从中记录结果,并一直看到它们。 Obviously it has not become invalid after the first time its onReceive() was called. 显然,它在第一次调用其onReceive()之后并没有变得无效。

I am wondering if this section of documentation perhaps applies only to BroadcastReceivers which are registered in the AndroidManifest ? 我想知道这部分文档是否仅适用于在AndroidManifest中注册的BroadcastReceivers And that it is simply incorrect or irrelevant to BroadcastReceivers that are dynamically created and registered? 并且它与动态创建和注册的BroadcastReceivers完全不正确或无关吗?

And of course, I am wondering what is proper clean up and derferencing for my dynamic receivers. 当然,我想知道对我的动态接收器来说适当的清理和递减是什么。

All you need to do for BroadcastReceivers in code is register and unregister them. 您需要使用代码对BroadcastReceivers进行的所有操作是注册和注销它们。 That statement is to inform you that you can't do any work outside of the onReceive , for example in another thread, and return a value back to the BroadcastReceiver . 该语句通知您,您不能在onReceive之外(例如在另一个线程中)进行任何工作,然后将值返回给BroadcastReceiver To do that you would get the BroadcastReceiver to start a Service . 为此,您可以让BroadcastReceiver启动Service

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM