Global status
- your friend.:)
Check the global string every time you need (say, before completion). You can also have a state enumeration. Or a flag to find out if the condition is real.
Recipe:
The more general problem you are facing is how to maintain state in several actions and in all parts of the application. A static variable (e.g. singleton) is the usual way to implement Java. However, I found that a more elegant way in Android is to associate your state with the application context.
As you know, each activity also represents a context that represents information about its execution environment in the broadest sense. Your application also has a context, and Android guarantees that it will exist as a single instance in your application.
The way to do this is to create your own subclass of android.app.Application , and then point that class in the application tag to your manifest. Now Android will automatically instantiate this class and make it available to your entire application. You can access it from any context using the Context.getApplicationContext () method (Activity also provides the getApplication () method, which has the same effect):
class MyApp extends Application { private String myState; public String getState(){ return myState; } public void setState(String s){ myState = s; } } class Blah extends Activity { @Override public void onCreate(Bundle b){ ... MyApp appState = ((MyApp)getApplicationContext()); String state = appState.getState(); ... } } class BlahBlah extends Service { @Override public void onCreate(Bundle b){ ... MyApp appState = ((MyApp)getApplicationContext()); String state = appState.getState(); ... } }
This has the same effect as a static variable or singleton, but integrates pretty well into the existing Android platform. Note that this will not work in all processes (should your application be one of the rare ones that has several processes).
Credits go to @Soonil
source share