这里记录一下某个提问。
先来看下当启动一个android app启动时发生了什么?
当一个app启动(冷启动)时,Android操作系统会启动一个进程,并指定一个唯一的进程id(pid)和分配一个进程表(process table)。
该进程启动一个DVM(Dalvik VM)实例,每个app运行在一个DVM中。DVM是干嘛的?它管理class loading,unloading, instance lifecycle, GC等。
一个static变量的生命周期:
当一个类被JVM装载(loaded)时,其所在的static变量生成;当该类被卸载(unloaded)时,该static变量销毁。
因此如果创建了一个static变量,它除了以下某种情况外,都会保留在JVM中:
1. 所在类unloaded
2. JVM shuts down
3. 进程dies
注意:当你切换到另外一个app的不同activity,而且上述3个情况都没有发生,static变量的值会一直存在。
可以通过以下代码来测试:
Note 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 null
- Initialize the static. print it -> value would be non null
- Hit the back button and go to home screen. Note: Home screen is another activity.
- Launch your activity again -> the static variable will be non-null
- Kill your application process from DDMS(stop button in the devices window).
- Restart your activity -> the static will have null value.
本文探讨了Android应用启动时的进程与DVM机制,并详细阐述了static变量的生命周期。static变量在类加载时创建,类卸载、JVM关闭或进程结束时销毁。在不同Activity间切换,只要不满足以上条件,static变量值将保持。实验表明,即使返回主页再打开应用,static变量仍保留其值,但通过DDMS停止应用进程后,重启Activity,static变量将恢复为null。

2万+

被折叠的 条评论
为什么被折叠?



