Are static variable truly “global” (system-wide) in Android?

为君一笑 提交于 2019-12-13 13:39:40

问题


A quick note at the very beginning to avoid false duplicates: There are tons of questions here about when static variables get cleared and how long they live. This is not what I'm asking about here.

If I have a static variable in a program on a PC and I launch two different copies of the program, then each copy will usually run in its own sandbox with its own private values for its static variables. So, they are not system-wide global (not sure if that is good terminology here).

Are there situations in Android where I can have multiple "instances" (word used loosely) of a static variable around? I don't think it's possible to have multiple copies of an Activity running in parallel in different sandboxes (although I'm not certain of this), but how about ConentProviders, IntentServices, or any other class that Android might randomly instantiate from potentially other processes?

Or, phrased differently, if I have a class with a static variable, am I guaranteed that every single instance of the class existing on the same device at the same time has access to the exact same static variable value?


回答1:


Static fields are accessible to all the classes running in the same process. If the Service, Application, BroadcastReceiver, ContentProvider or Activity is running in a separate process then it will have a different memory space, thus won't see static fields from the other processes. You can force a component to run on another process by specifying its' it in the AndroidManisfest (e.g. android:process="string" http://developer.android.com/guide/topics/manifest/receiver-element.html)




回答2:


For Android, I believe that static variable are not system-wide. It is only available in the instance of the application. So let say Activity A instantiate a static variable, Activity B will be able to use the static variable. Activity A and B belong to the same application. As long as the application doesn't close, the static variable should remained instantiated. However, as long as the application is close, the static variable will be killed and need to be reinstantiated. Note that I used the term application and not activity.

As for ContentProvider, Android normally will generate a directory for that particular application for all the data created by the application.



来源:https://stackoverflow.com/questions/33885474/are-static-variable-truly-global-system-wide-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!