Search code examples
androidglobalsandboxstatic-variables

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


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?


Solution

  • 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)