Activity isFinishing()判断Activity的状态

本文探讨了Android Activity生命周期中的关键问题,特别是在finish()调用后onDestroy()未被执行的情况及其原因。文章详细解释了如何通过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;
}

------------------------------------------------------------------------------------------------------

刚刚一个BUG让我发现,如果 activity 实现了一个回调接口,然后使用 this 设置给需要回调接口的方法,这种应用场景比较常见,最常见的就是实现 onClickListener 接口,然后 findViewById().setOnClickListenr(this)


如果,这个回调接口设置到了一个静态对象(单例模式),当 activity finish() 的时候(按返回键,回到桌面),则activity 不会被调用 onDestroy() ,原因可能是 activity 对象还在被引用!

此时你再点击图标回到应用,onCreate() 再次调用!

很明显,如果你把资源释放放在了 onDestroy() 里面,就会导致内存泄露!


那有没有解决办法呢?有的

你可以在 onPause() 方法里面判断 isFinishing() ,正常调用 finish() 后 activity 的回调过程是 onPause、onStop、onDestroy ,倘若出现上面的情况,只到 onPause!但是 isFinishing() 标志还是为 true !你可以释放资源了。 

来源:http://blog.youkuaiyun.com/z1074971432/article/details/10517449


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值