在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 !你可以釋放資源了。
以上這篇Activity isFinishing()判斷Activity的狀態實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。
新聞熱點
疑難解答