[Android]static变量的生命周期

本文探讨了Android应用启动时的进程与DVM机制,并详细阐述了static变量的生命周期。static变量在类加载时创建,类卸载、JVM关闭或进程结束时销毁。在不同Activity间切换,只要不满足以上条件,static变量值将保持。实验表明,即使返回主页再打开应用,static变量仍保留其值,但通过DDMS停止应用进程后,重启Activity,static变量将恢复为null。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里记录一下某个提问。

先来看下当启动一个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:

  1. Print the uninitialized static in onCreate of your activity -> should print null
  2. Initialize the static. print it -> value would be non null
  3. Hit the back button and go to home screen. Note: Home screen is another activity.
  4. Launch your activity again -> the static variable will be non-null
  5. Kill your application process from DDMS(stop button in the devices window).
  6. Restart your activity -> the static will have null value.

问题来源:
http://stackoverflow.com/questions/1944369/android-static-object-lifecycle

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值