Android 静态对象生命周期 [英] Android static object lifecycle

查看:37
本文介绍了Android 静态对象生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建事件搜索应用程序,我们从一个屏幕设置搜索条件并填充到另一个屏幕,然后用户可以从第 3 个屏幕编辑搜索条件并转到第 4 个屏幕.

I am creating event search application, we set search criteria from one screen populate in another screen then user can edit search criteria from 3rd screen and goes to 4th screen.

为了完成上述任务,我使用了静态对象,它记住了应用程序周围的值,我不需要做任何额外的事情.

To achieve above task i am using static object which remember the values around the application and i don't need to do any thing extra.

但我担心如果内存不足,android 中的静态对象生命周期是否会被 android 删除静态对象???

But i am afraid if about static object life cycle in android if low memory found android delete static objects ???

由于android支持多任务,如果用户切换到另一个应用程序,当用户回来时应用程序开始疯狂,静态对象在多任务时会被删除吗???任何的想法 ??并建议通过单例方法保存静态对象是更好的方法???

As android supports multi tasking, if user switches to another application and when user comes back application start acting crazy, does static object get removed when it multi task ??? any idea ?? and also suggest holding static object via singleton method is better approach ???

推荐答案

让我们从一些背景开始:启动应用程序时会发生什么?
操作系统启动一个进程并为其分配一个唯一的进程id并分配一个进程表.一个进程启动一个DVM(Dalvik VM)的实例;每个应用程序都在 DVM 内运行.
DVM 管理类加载卸载、实例生命周期、GC 等.

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.

静态变量的生命周期:当类被JVM加载时,静态变量存在,在类卸载时消亡.

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.

因此,如果您创建一个 android 应用程序并初始化一个静态变量,它将保留在 JVM 中,直到发生以下情况之一:
1.类被卸载
2.JVM关闭
3.进程终止

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 unloaded
2. the JVM shuts down
3. the process dies

请注意,当您切换到另一个应用程序的不同活动时,静态变量的值将保持不变,并且上述三种情况均不会发生.如果以上三种情况中的任何一种发生,静态将失去其价值.

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. 在活动的 onCreate 中打印未初始化的静态 -> 应该打印 null
  2. 初始化静态.打印它 -> 值将是非空
  3. 点击后退按钮并转到主屏幕.注意:主屏幕是另一个活动.
  4. 再次启动您的活动 -> 静态变量将为非空
  5. 从 DDMS 中终止您的应用程序进程(设备窗口中的停止按钮).
  6. 重新启动您的活动 -> 静态将具有空值.

希望有所帮助.

这篇关于Android 静态对象生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆