您的位置:首页 > 移动开发 > Android开发

Android 静态变量不可信

2014-11-04 22:07 113 查看
引语在以前公司上看过一篇文章,大概是说 Pony 跟朋友的聊天消息乱码,初始还以为他们在用潮汕话聊呢(开玩笑的),按常规逻辑很难想明白,然后根据 Android 不可信的思路,终于顺利找到原因,具体忘了是什么原理,大概是存取结果不一致之类的吧。
最近有在思考,写一个方法的时候,怎么知道将会在主线程还是非主线程运行的呢?后面想到,应该是有“不可信”的原则,即不要相信外面调用的方法所在的线程。有一个 NullPointerException 的报错,一直想不明白,明明都已经赋值了,却还会报错。
Android 应该会在它认为需要的时候回收内存,包括 Static 变量,然后被使用时,再自动初始化,但初始化是根据类初始声明来的,所以后面有赋值的,不一定会保证一直都有。
这里应该是 static 变量被回收,然后再初始化,就没值了。
故应该多给自己一个思想:Static 变量不可信,使用时要先判断。另外也需要注意,静态变量有时会一直占用内存,导致性能变差。
所以一方面,要防止它没了,一方面,又注意它一直都在的问题。参考:Android静态变量的生命周期Android开发之警惕static变量使用
Android static静态成员变量的使用误区不解
发现在自己做事件中心,或者是 activty manage 时,都会定义类似public staitc final List xxx = new List..的代码,这个看起来也没什么更好的办法;
那么问题来了,系统什么时候会回收这个 list 的内容呢?我现在的理解是:只要程序没被kill 掉或者 crash ,那里的内容就不会被回收。有 staticOverflow 找到两个类似但又不完全一样的解答:
一:Static variables are associated with a class and they will live as long as the class is in the memory,and destroy when class gets unloaded (which very rarely happens). It can happen when-
-You force stop your app.
-Application crashes.
-You clear your app data.
-Switch off your Device(Shutdown DVM).


二:

Lets start with a bit of background: What happens when you start an application?The OS starts a process and assigns it a unique process id and allocates a process table.A process start an instance of DVM(Dalvik VM); Each application runs inside a DVM.A DVM manages class loading unloading, instance lifecycle, GC etc.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.So 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 unloaded2. the JVM shuts down3. the process diesNote that the value of the static variable will persist when you switch to a different activity of another application and none of the above three happens. Should any of the above three happen the static will lose its value.You can test this with a few lines of code:print the uninitialized static in onCreate of your activity -> should print nullinitialize the static. print it -> value would be non nullHit the back button and go to home screen. Note: Home screen is another activity.Launch your activity again -> the static variable will be non-nullKill your application process from DDMS(stop button in the devices window).Restart your activity -> the static will have null value.Hope that helps.
来自:http://stackoverflow.com/questions/1944369/android-static-object-lifecycle-application-act-crazy/1944564#1944564
我在两个论坛也发帖提问了:
http://segmentfault.com/q/1010000002445149?_ea=95604http://www.eoeandroid.com/thread-559267-1-1.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: