You can say: “当活动销毁/暂停时,我是否应该移除任何监听器?Android Studio”

huangapple go评论77阅读模式
英文:

Should I remove any listeners when activity is destroyed/paused? Android Studio

问题

我在想当应用程序进入后台/销毁时,是否应该明确移除任何观察者/监听器,或者是不是不需要移除,因为安卓系统知道何时移除?

谢谢 You can say: “当活动销毁/暂停时,我是否应该移除任何监听器?Android Studio”

英文:

I wondered if I should explicitly remove any observers/listeners when the application goes to background/destroyed.
or should'nt I remove becuase the android machine knows when to remove?

thanks You can say: “当活动销毁/暂停时,我是否应该移除任何监听器?Android Studio”

答案1

得分: 0

如果你的意思是UI监听器,比如按钮的onClickListener,那么现在没问题,因为当应用程序在后台时,不会执行任何操作。当活动被销毁时,所有监听器也会被销毁。

但是,如果你的活动正在观察另一个类,并根据该类的更改更新自身,那么你需要在活动的onStart中注册活动,在onStop()中取消注册。否则,由于活动不处于活动状态,可能会引发异常。

另一种需要注意的情况是,当你在活动内部创建一个Thread时,这是一个静态内部类,并且引用了你的活动。只要线程在运行,活动就不会被垃圾回收。如果活动在线程完成之前被销毁,这可能会导致内存泄漏。

英文:

if you mean UI listeners like onClickListener for a button then now that's ok because when the app is in the background no action could be taken. and when activity is destroyed all the listeners will be destroyed too.

but if your activity is observing another class and updates itself according to changes in that class then you need to register activity in onStart and unregister in onStop() of the activity. otherwise, it could cause exceptions since the activity is not active.

another case you should watch out for is when you create a Thread inside your activity, which is a static inner class and has a reference to your activity. and as long as the Thread is running the activity won't get garbage collected. this could lead to memory leaks if activity dies before the thread is done like

huangapple
  • 本文由 发表于 2020年8月12日 17:29:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63373691.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定