在Android应用程序中使用静态类变量是否安全? [英] Is it safe to use static class variables in an android application

查看:104
本文介绍了在Android应用程序中使用静态类变量是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道扩展Application类以提供全局存储的技术.但是,就我而言,我正在为库函数编写一个类,因此不希望强迫该类的用户走这条路.我需要一些静态类变量.我看到在StackOverflow中传递引用可能不安全.但是,我已经尝试了使用同一类的两个不同的应用程序,即使在多窗口模式下在Galaxy S3上并行运行两个应用程序时,静态类变量仍保持独立.

I am aware of the technique of extending the Application class to provide global storage. However in my case I am writing a class for a library function, so do not wish to force users of the class down this path. I have a requirement for some static class variables. I have seen passing references in StackOverflow that these might not be safe. However I've tried two different applications using the same class, and even when running both applications side by side on a Galaxy S3 in multi-window mode, the static class variables remain separate.

因此,可以对Android内部知识有深入了解的人可以确认这是否安全.

So, can someone with an in depth knowledge of Android internals confirm if this is safe or not.

如果不安全,我可以将变量包装在嵌套类中,并使用应用程序包名称作为键将其添加到Serializable静态HashMap中.这将迫使他们安全.但是,如果这不是必需的,那么我宁愿不这样做.

If it is not safe, I can wrap the variables in a nested class and add them to a Serializable static HashMap, using the application package name as the key. This will force them to be safe. However if this is not necessary, then I'd rather not do it.

推荐答案

我已经看到在StackOverflow中传递引用可能不安全.

I have seen passing references in StackOverflow that these might not be safe.

它们不安全,因为您的过程将不时终止,从而消除了静态数据成员(以及您的自定义 Application ).因此,静态数据成员对于缓存很有用,而对缓存则没有什么好处.

They are not "safe" insofar as your process will be terminated from time to time, wiping out your static data members (and your custom Application, for that matter). Hence, static data members are good for a cache and not much else.

在此范围内,它们是安全的".

Within that scope, they are "safe".

您只需要确保此数据存储在持久性文件(例如文件)的某个位置,否则可以在过程终止并稍后重新启动后重新生成.这和 Application 一样.

You just need to make sure that this data is either stored somewhere persistent (e.g., file) or otherwise can be regenerated once the process is terminated and later is started up again. This is no different than with Application.

但是我尝试使用同一类尝试两个不同的应用程序,即使在多窗口模式下在Galaxy S3上并排运行两个应用程序时,静态类变量仍保持独立.

However I've tried two different applications using the same class, and even when running both applications side by side on a Galaxy S3 in multi-window mode, the static class variables remain separate.

正确.这些是单独的过程,带有您的类和对象的单独副本.

Correct. Those are separate processes, with separate copies of your class and objects.

这篇关于在Android应用程序中使用静态类变量是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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