英文:
Should I remove any listeners when activity is destroyed/paused? 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
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论