基于上下文的 Android 广播接收器绝对需要 unregisterReceiver 吗?
Is unregisterReceiver absolutely required for a context-based Android Broadcast Receiver?
Broadcasts 的 Android 开发者页面是这样描述广播接收器及其接收广播的:
Context-registered receivers receive broadcasts as long as their
registering context is valid. For an example, if you register within
an Activity context, you receive broadcasts as long as the activity is
not destroyed.
它还说:
Be mindful of where you register and unregister the receiver, for
example, if you register a receiver in onCreate(Bundle) using the
activity's context, you should unregister it in onDestroy() to prevent
leaking the receiver out of the activity context.
对我来说,这意味着如果你在 activity 的上下文中注册了一个接收器,但在 activity 被销毁时不注销它,你将不再接收广播,但你会仍然 "leak" 接收者。 这是正确的吗?
我之所以想确切地知道这一点,是因为我想将一个基于上下文的广播接收器包装在一个 in 对象中,并且我希望这个对象的接口是这样的:
class DoesManyThings {
DoesManyThings(Context context) {
context.registerReceiver(...);
}
}
我将在 activity 的 onCreate
方法中创建这个对象。
但是如果我这样做,我将不知道何时取消注册接收者,我将不得不添加一个显式方法,如 void cleanup()
,我必须在 onDestroy
调用它。我想知道我是否必须执行此显式清理。
您可以通过调用
为生命周期回调注册您的组件
activity.getApplication().registerActivityLifecycleCallbacks()
然后,监听 Activity
的 onDestroy()
回调并在那里取消注册接收器。
有点矫枉过正,但达到了目的。
我相信你的理解是正确的——一旦activity被摧毁,你就不会再收到广播了。但是,由于您还没有取消注册,您仍然可能会泄漏该对象。 (至少,您会在 logcat 中收到关于此的不愉快警告消息)
从代码清洁度的角度来看,感觉您应该也有一个清理方法。将来,您可能会扩展 "DoesManyThings" 对象的功能,而您添加的其他状态在 Activity.
的生命周期之外可能不太安全。
但是请注意,不保证一定会调用 onDestroy。您可能希望考虑转向 onStart/onStop - 但这取决于动态接收器的具体用例。
Broadcasts 的 Android 开发者页面是这样描述广播接收器及其接收广播的:
Context-registered receivers receive broadcasts as long as their registering context is valid. For an example, if you register within an Activity context, you receive broadcasts as long as the activity is not destroyed.
它还说:
Be mindful of where you register and unregister the receiver, for example, if you register a receiver in onCreate(Bundle) using the activity's context, you should unregister it in onDestroy() to prevent leaking the receiver out of the activity context.
对我来说,这意味着如果你在 activity 的上下文中注册了一个接收器,但在 activity 被销毁时不注销它,你将不再接收广播,但你会仍然 "leak" 接收者。 这是正确的吗?
我之所以想确切地知道这一点,是因为我想将一个基于上下文的广播接收器包装在一个 in 对象中,并且我希望这个对象的接口是这样的:
class DoesManyThings {
DoesManyThings(Context context) {
context.registerReceiver(...);
}
}
我将在 activity 的 onCreate
方法中创建这个对象。
但是如果我这样做,我将不知道何时取消注册接收者,我将不得不添加一个显式方法,如 void cleanup()
,我必须在 onDestroy
调用它。我想知道我是否必须执行此显式清理。
您可以通过调用
为生命周期回调注册您的组件activity.getApplication().registerActivityLifecycleCallbacks()
然后,监听 Activity
的 onDestroy()
回调并在那里取消注册接收器。
有点矫枉过正,但达到了目的。
我相信你的理解是正确的——一旦activity被摧毁,你就不会再收到广播了。但是,由于您还没有取消注册,您仍然可能会泄漏该对象。 (至少,您会在 logcat 中收到关于此的不愉快警告消息)
从代码清洁度的角度来看,感觉您应该也有一个清理方法。将来,您可能会扩展 "DoesManyThings" 对象的功能,而您添加的其他状态在 Activity.
的生命周期之外可能不太安全。但是请注意,不保证一定会调用 onDestroy。您可能希望考虑转向 onStart/onStop - 但这取决于动态接收器的具体用例。