Android编程之Activity中onDestroy()调用分析
本文分析了Android编程之Activity中onDestroy()调用方法。分享给大家供大家参考,具体如下:
刚刚一个BUG让我发现,如果 activity 实现了一个回调接口,然后使用 this 设置给需要回调接口的方法,这种应用场景比较常见,最常见的就是实现 onClickListener 接口,然后 findViewById().setOnClickListenr(this)
如果,这个回调接口设置到了一个静态对象(单例模式),当 activity finish() 的时候(按返回键,回到桌面),则activity 不会被调用 onDestroy() ,原因可能是 activity 对象还在被引用!
此时你再点击图标回到应用,onCreate() 再次调用!
很明显,如果你把资源释放放在了 onDestroy() 里面,就会导致内存泄露!
那有没有解决办法呢?有的
你可以在 onPause() 方法里面判断 isFinishing() ,正常调用 finish() 后 activity 的回调过程是 onPause、onStop、onDestroy ,倘若出现上面的情况,只到 onPause!但是 isFinishing() 标志还是为 true !你可以释放资源了。
我们来看下 onDestroy 的官方解释:
protected void onDestroy () Added in API level 1 Perform any final cleanup before an activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method. Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away. Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
希望本文所述对大家Android程序设计有所帮助。
- Material Design系列之Behavior实现Android知乎首页
- php、java、android、ios通用的3des方法(推荐)
- Android5.0中Material Design的新特性
- Android数据加密之Des加密详解
- Android程序开发之使用Design包实现QQ动画侧滑效果和滑动菜单导航
- Android App仿QQ制作Material Design风格沉浸式状态栏
- 详解Android Material Design自定义动画的编写
- 学习Android Material Design(RecyclerView代替ListView)
- android:descendantFocusability方法介绍
- Android数据加密之Des加密
相关文章
android 限制某个操作每天只能操作指定的次数(示例代码详解)
这篇文章主要介绍了android 限制某个操作每天只能操作指定的次数,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-06-06
Ubuntu中为Android增加硬件抽象层(HAL)模块访问Linux内核驱动程序
本文主要介绍在Ubuntu上为Android HAL模块访问Linux内核驱动程序,这里给大家提供方法和一个小的测试程序代码,以及常遇到的问题和解决方法,有需要的小伙伴可以参考下2016-08-08
设置界面开发Preference Library数据重建机制详解
这篇文章主要为大家介绍了设置界面开发利器Preference Library数据重建机制详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-10-10
Android 使用PopupWindow实现弹出更多的菜单实例详解
最近想要做一个弹出更多的菜单,而原生的弹出菜单却不是我们想要的效果,所以必然要自定义菜单。接下来通过本文给大家介绍android 使用popupwindow实现弹出更多的菜单实例详解,需要的朋友可以参考下2017-04-04
Android自定义view利用Xfermode实现动态文字加载动画
这篇文章主要介绍了Android自定义view利用Xfermode实现动态文字加载动画,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-07-07


最新评论