Activity中isFinishing()如何判断Activity的状态-成都创新互联网站建设

关于创新互联

多方位宣传企业产品与服务 突出企业形象

公司简介 公司的服务 荣誉资质 新闻动态 联系我们

Activity中isFinishing()如何判断Activity的状态

小编给大家分享一下Activity中isFinishing()如何判断Activity的状态,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

红山网站建设公司创新互联,红山网站设计制作,有大型网站制作公司丰富经验。已为红山上千余家提供企业网站建设服务。企业网站搭建\外贸网站制作要多少钱,请找那个售后服务好的红山做网站的公司定做!

在Activity中调用finish()或按返回键退出时,若有资源被其他对象引用不能释放(如context被某个单例对象引用或正在线程中被使用),则activity不会被调用onDestory()方法。

isFinishing() 可用来判断Activity是否处于活跃状态(false)还是等待回收状态(true)。

isDestroyed() 根据源码注释可知,只有onDestroy()方法被调用后它才返回true,因此实际用处不大。

查看源代码中的注释:

/**
 * Check to see whether this activity is in the process of finishing,
 * either because you called {@link #finish} on it or someone else
 * has requested that it finished. This is often used in
 * {@link #onPause} to determine whether the activity is simply pausing or
 * completely finishing.
 *
 * @return If the activity is finishing, returns true; else returns false.
 *
 * @see #finish
 */
public boolean isFinishing() {
 return mFinished;
}
/**
 * Returns true if the final {@link #onDestroy()} call has been made
 * on the Activity, so this instance is now dead.
 */
public boolean isDestroyed() {
 return mDestroyed;
}

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 !你可以释放资源了。

以上是“Activity中isFinishing()如何判断Activity的状态”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!


新闻标题:Activity中isFinishing()如何判断Activity的状态
链接地址:http://kswsj.cn/article/jcepoj.html

其他资讯