您的位置:首页 > 其它

Activity isFinishing()判断Activity的状态实例

2018-03-23 09:15 686 查看

在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的状态实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息