android中少用靜態變量(android靜態變量static生命周期)


在android中,要少用靜態變量。

我現在做的一個應用中,之前的開發人員使用靜態變量來存儲cookie,這個全局的靜態變量用來驗證身份。

這時客戶反應,應用長時間不使用,再次使用,會提示身份過期。

后來經查,問題基本確定在靜態變量上。

上stackoverflow查了android中static變量的生命周期,有人這么說

Lifetime of a static variable: A static variable comes into existence when a class is loaded by the JVM and dies when the class is unloaded,if you create an android application and initialize a static variable, it will remain in the JVM until one of the following happens:

1. the class is unloaded
2. the JVM shuts down
3. the process dies

我們應用出現的情況應該就是進程被系統殺掉導致的。

后來這個情況也發現了,就是不斷地打開應用,當系統內存不夠用時,應用進程會被殺掉。這時再打開應用,就出現了身份過期,也即靜態變量為空的情況

靜態變量,要慎用!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM