简体   繁体   English

在 Android 上,是否有必要在活动被破坏时移除传感器侦听器?

[英]On Android, is it necessary to remove a sensor listener when an activity is destroyed?

On the Android platform, Activity objects may register SensorEventListener 's.在 Android 平台上, Activity对象可能会注册SensorEventListener There are examples that show the Listener object being explicitly removed when the Activity to which it belongs is destroyed.有一些示例显示Listener对象在其所属的Activity被销毁时被显式删除。 But other examples do not include this step, suggesting that this may be done automatically.但其他示例不包括这一步,表明这可能是自动完成的。 That would make the extra bit of code redundant.这会使多余的代码变得多余。 I am not sure if that is true.我不确定这是否属实。

My question is: if a SensorEventListener is registered by an Activity , what resources (if any) will remain allocated to the Listener if it is not explicitly removed when the Activity is destroyed?我的问题是:如果SensorEventListener是由Activity注册的,如果在Activity销毁时没有明确删除,哪些资源(如果有)将继续分配给Listener

Yes, you need to remove it yourself before Activity destruction.是的,您需要在 Activity 销毁之前自行删除它。 If you don't, you'll cause a memory leak.如果不这样做,则会导致内存泄漏。 Depending on your implementation, it could be a bad one.根据您的实现,它可能是一个糟糕的实现。

If the entire app is killed, then the listener goes away because everything in the app goes away.如果整个应用程序被杀死,那么监听器就会消失,因为应用程序中的一切都消失了。 But I wouldn't rely on specific behavior causing the app to die- just unregister it in onDestroy of whatever Activity you register it in. The easiest way to do that is to use a LifecycleObserver但我不会依赖导致应用程序死亡的特定行为 - 只需在您注册它的任何活动的 onDestroy 中取消注册它。最简单的方法是使用 LifecycleObserver

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

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