Using static variables in Android

Does android use static variables? Recommended practice? For example, when implementing the Singleton pattern in Java, I usually do:

private static A the_instance; public static A getInstance() { if (the_instance == null) { the_instance = new A(); } return the_instance; } 

Also, when is the Android JVM cleared?

Thank.

+54
java android dalvik
Mar 19 '10 at 8:51
source share
4 answers
Fields

static tied to the Class instance as a whole, which in turn is tied to the ClassLoader that loaded the class. the_instance will be unloaded when the entire ClassLoader is restored. I am 90% sure that this happens when Android destroys the application (and not when it goes into the background or pauses, but completely shuts down.)

So, think of it as life while your application is running. Is Singleton a good idea? People have different views. I think it's good to use it appropriately. I don’t think the answer will change much on Android. Memory usage is not a problem in itself; if you need to load a bunch of material in memory, this is either a problem or it doesn't exist, regardless of whether you encapsulate the data in Singleton.

+61
Mar 19 '10 at 9:30
source share

I think static variables are fine.

This is what Android doc says:

http://developer.android.com/guide/appendix/faq/framework.html

How to transfer data between Activity / Services in one application?

Open static field / method

An alternative way to make data available for all activities / services is to use public static fields and / or methods. You can access these static fields from any other class in your application. To share an object, the action that your object creates sets up a static field that points to that object, and any other action that this object wants to use simply accesses this static field.

+15
03 Sep '10 at 20:00
source share

I'm not sure if this approach is good for a mobile platform where you have limited memory. Not to mention the fact that the application will run on the device with several tasks.

I think this approach can call memory from the device, but I don't have a document to support this. Perhaps someone who is more educated than me can share their thoughts.

0
Mar 19 '10 at 9:26
source share

No. Do not do this! Singleton is an antipater! . Instead, use dependency injection, whether through a framework (for example, through Dagger or Roboguice ) or explicitly passing an instance of an object.

-four
Mar 19 '10 at 9:31
source share



All Articles