Android Application life cycle and singelton

北慕城南 提交于 2019-12-05 13:04:59

Since "mInstance" is a static variable it will not get null when you close your application. Closing of application doesn't means that your application got destroyed.

Also there is no concept of Closing your Android app. If you get out of your app it will not get destroyed at the same time. Android OS handles it internally when to close the app when it is no more in use. In case of memory shortage when android decides to destroy the app then this static variable will also got null.

You can not control when exactly Java objects become garbage collected. An object becomes eligible for garbage collection when there are no more (non-circular) references to it. With Android, further, you can not control when your Activity gets removed from memory.

why does it happening?

what am I missing?

when android garbage collecting static members belongs to application?

Ok first, as others said, there is no close application concept on Android as the android OS manages lifecycle of your application process on their own.

Second, you did the wrong test - if instead of closing all apps you would do the opposite - that is - fill up memory by starting more and more apps, then eventually your application's memory would be cleaned up to be used by other applications and this includes all static mebers as well as instance members! then, you will see that the static variable WILL BE NULL as you expected.

They just "lazily" clean up memory, if there's enough memory then you application might never get cleaned up.

Actually, there is no way around it, as far as i know, there is no way to grauntee an object would not be cleaned up at any point from the device memory. in somecases it leads to bad behaviour. such as if the singleton does heavy processing on its creation, calling getInstance might get your UI stuck, or even make your app crash due to irresponsibleness.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!