欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Activity isFinishing()判斷Activity的狀態(tài)實例

 更新時間:2018年03月23日 09:15:59   作者:wangsf1112  
下面小編就為大家分享一篇Activity isFinishing()判斷Activity的狀態(tài)實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

在Activity中調(diào)用finish()或按返回鍵退出時,若有資源被其他對象引用不能釋放(如context被某個單例對象引用或正在線程中被使用),則activity不會被調(diào)用onDestory()方法。

isFinishing() 可用來判斷Activity是否處于活躍狀態(tài)(false)還是等待回收狀態(tài)(true)。

isDestroyed() 根據(jù)源碼注釋可知,只有onDestroy()方法被調(diào)用后它才返回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() 調(diào)用研究

剛剛一個BUG讓我發(fā)現(xiàn),如果 activity 實現(xiàn)了一個回調(diào)接口,然后使用 this 設(shè)置給需要回調(diào)接口的方法,這種應用場景比較常見,最常見的就是實現(xiàn) onClickListener 接口,然后 findViewById().setOnClickListenr(this)

如果,這個回調(diào)接口設(shè)置到了一個靜態(tài)對象(單例模式),當 activity finish() 的時候(按返回鍵,回到桌面),則activity 不會被調(diào)用 onDestroy() ,原因可能是 activity 對象還在被引用!

此時你再點擊圖標回到應用,onCreate() 再次調(diào)用!

很明顯,如果你把資源釋放放在了 onDestroy() 里面,就會導致內(nèi)存泄露!

那有沒有解決辦法呢?

有的 你可以在 onPause() 方法里面判斷 isFinishing() ,正常調(diào)用 finish() 后 activity 的回調(diào)過程是 onPause、onStop、onDestroy ,倘若出現(xiàn)上面的情況,只到 onPause!但是 isFinishing() 標志還是為 true !你可以釋放資源了。

以上這篇Activity isFinishing()判斷Activity的狀態(tài)實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論