How to declare global variables in Android? ---application subclasses

Source: Internet
Author: User

I wrote this answer on ' When Android is relatively new, and there were many not well established areas in Android Development. I have added a long addendum at the bottom of this post, addressing some criticism, and detailing a philosophical disagree ment I has the use of singletons rather than subclassing application. Read it at your own risk.

ORIGINAL ANSWER:

The more general problem-encountering is-how-to-save state across several activities and all parts of your Applica tion. A static variable (for instance, a singleton) is a common Java-by-the-achieving this. I have found however, which a more elegant-in-the-Android is to associate your state with the application context.

As you are know, each Activity is also a Context, which was information about its execution environment in the broadest sense. Your application also have a context, and Android guarantees that it'll exist as a single instance across Your Applicatio N.

The your own subclass of Android.app.Application, and then specify that class in the Applicati On tag in your manifest. Now Android would automatically create an instance of this class and make it available for your entire application. You can access it by context using the Context.getApplicationContext() method ( Activity also provides a method which has the getApplication() exact same EFFEC T). Following is a extremely simplified example, with caveats to follow:

classMyAppextendsApplication {PrivateString MyState;  PublicString getState () {returnMyState; }   Public voidsetState (String s) {MyState=s; }}classBlahextendsActivity {@Override Public voidonCreate (Bundle b) {... MYAPP appState=( MyApp) Getapplicationcontext ()); String State=appstate.getstate (); ...  }}

This have essentially the same effect as using a static variable or singleton, but integrates quite well into the existing Android Framework. Note that this won't work across processes (should your app is one of the rare ones that have multiple processes).

Something to note from the example above; Suppose we had instead done something like:

class extends Application {  private*/*;    Public String getState () {    return  mystate;  }}

Now this slow initialization (such as hitting disk, hitting network, anything blocking, etc) would be performed every time Application is instantiated! You could think, well, that's the only once for the process and I'll have to pay the cost anyways, right? For instance, as Dianne Hackborn mentions below, it's entirely possible for your process to be instantiated-just-to Han Dle a background broadcast event. IF your broadcast processing has no need for this state you have potentially just do a whole series of complicated and S Low operations to nothing. Lazy instantiation is the name of the game here. The following is a slightly more complicated the by using application which makes more sense for anything but the simplest of uses:

classMyAppextendsApplication {PrivateMystatemanager Mystatemanager =NewMystatemanager ();  PublicMystatemanager Getstatemanager () {returnMystatemanager; }}classMystatemanager {Mystatemanager () {/*This should is fast*/} String getState () {/*if necessary, perform blocking calls here*/    /*Make sure to deal with any multithreading/synchronicity issues*/    ...    returnState ; }}classBlahextendsActivity {@Override Public voidonCreate (Bundle b) {... Mystatemanager Statemanager=( MyApp) Getapplicationcontext ()). Getstatemanager (); String State=statemanager.getstate (); ...  }}

While I prefer application subclassing to using singletons here as the more elegant solution, I would rather developers us e singletons if really necessary over not thinking @ all through the performance and multithreading implications of Assoc Iating state with the application subclass.

Note 1: Also as Anticafe commented, in order to correctly tie your application override to your application a tag are necessary in The manifest file. Again, see the Android docs for more info. An example:

< Application      Android:name = "MY.APPLICATION.MYAPP"       android:icon= "..."     android:label= "..."></  application>

Note 2: user608578 asks below how this works with managing native object lifecycles. I am not up to speed on using native code with Android in the slightest, and I am not qualified to answer how that would I Nteract with my solution. If Someone does has an answer to this, I am willing to credits them and put the information in this post for maximum Visib Ility.

Addendum:

As some people has noted, this is  not  a solution for  Persistent & Nbsp;state, something I perhaps should has emphasized more in the original answer. i.e. this was not meant-be-a solution for saving user or other information so is meant to be persisted across Applicat Ion lifetimes. Thus, I consider most criticism below related to applications being killed at any time, etc ..., moot, as anything that Eve R needed to is persisted to disk should is stored through an application subclass. It is meant-to-be-a solution for storing temporary, easily re-creatable application state (whether a user was logged in for example) and components which is a instance (Application network manager for example) ( not  si ngleton!) in nature.

Dayerman have been kind enough to point out a interesting conversation with Reto Meier and Dianne hackborn in Which use of application subclasses are discouraged in favor of Singleton patterns. Somatik also pointed out something of this nature earlier, although I didn ' t see it at the time. Because of Reto and Dianne ' s roles in maintaining the Android platform, I cannot in good faith recommend ignoring their ad Vice. What they say, goes. I do wish to disagree with the opinions, expressed with regards to preferring Singleton over application subclasses. In my disagreement I'll be making use of concepts best explained In this stackexchange explanation of the Singleton The design pattern, so, and do not has the to define terms in this answer. I highly encourage skimming the link before continuing. Point by point:

Dianne states, "There is no reason-subclass from application. It is no different than making a singleton ... " This first claim is incorrect. There is both main reasons for this. 1) The application class provides a better lifetime guarantee for an application developer; It is guaranteed to the lifetime of the application. A Singleton is not explicitly tied to the lifetime of the application (although it is effectively). This could be a non-issue to your average application developer, but I would argue this is exactly the type of contract the Android API should is offering, and it provides much more flexibility to the Android system as well, by minimizing the Li Fetime of associated data. 2) The application class provides the application developer with a single instance holder for state, which is very differe NT from a Singleton holder of state. For a list of the differences, see the Singleton explanation link above.

Dianne continues, "... just likely to being something you regret on the future as you find your application object becoming th Is big tangled mess of what should be independent application logic. " This was certainly not incorrect, but this is a reason for choosing Singleton over application subclass. None of Diane ' s arguments provide a reason that using a Singleton are better than an application subclass, all she attempts To establish are that using a Singleton are no worse than an application subclass, which I believe is false.

She continues, "and this leads more naturally to how you should be managing these things--initializing them on demand." This ignores the fact, there is no reason you cannot initialize on demand using a application subclass as well. Again there is no difference.

Dianne ends with "the framework itself have tons and tons of singletons for all the little GKFX data it maintains for The app, such as caches of loaded resources, pools of objects, etc. It works great. " I am not arguing this using singletons cannot work fine or is not a legitimate alternative. I am arguing that singletons does not provide as strong a contract with the Android system as using a application subclass, and further that using singletons generally points to inflexible design, which are not easily modified, and leads to many Problems down the road. IMHO, the strong contract the Android API offers to developer applications are one of the most appealing and pleasing aspec TS of programming with Android, and helped leads to early developer adoption which drove the Android platform to the succes S it has today. Suggesting using singletons is implicitly moving away from a strong API contract, and in my opinion, weakens the Android F Ramework.

Dianne have commented below as well, mentioning a additional downside to using application subclasses, they may encourage Or make it easier to write less performance code. This is very true, and I has edited this answer to emphasize the importance of considering perf here, and taking the Corr ECT approach if you ' re using application subclassing. As Dianne states, it's important to remember that your application class would be instantiated every time your process is Loaded (could be multiple times @ Once if your application runs in multiple processes!) even if the process was only being Loaded for a background broadcast event. It is therefore important to use the application class more as a repository for pointers to GKFX components of your APPL Ication rather than as a place to does any processing!

I Leave you and the following list of downsides to singletons, as stolen from the earlier Stackexchange link:

    • Inability to use abstract or interface classes;
    • inability to subclass;
    • High coupling across, the application (difficult to modify);
    • Difficult to test (can ' t fake/mock in unit tests);
    • Difficult to parallelize in the case of mutable state (requires extensive locking);

and add my own:

    • Unclear and unmanageable lifetime contract unsuited for Android (or more other) development;

via:http://stackoverflow.com/questions/708012/how-to-declare-global-variables-in-android/708317#708317

How to declare global variables in Android? ---application subclasses

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.