Android-global variables are very powerful, android-global variables
As you know, each Activity is also a Context, which is 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 using SS your application.
The way to do this is to create your own subclassAndroid. app. Application, And then specify that class in the application tag in your manifest. now Android will automatically create an instance of that class and make it available for your entire application. you can access it from any context using the Context. getApplicationContext () method (Activity also provides a method getApplication () which has the exact same effect ):
Java code
- 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 ();
- ...
- }
- }
This has essential tially the same effect as using a static variable or singleton,
But integrates quite well into the existing Android framework.
Note that this will not work until SS processes (shocould your app be one of the rare ones that has multiple processes ).
Then add the application to manifest:
Xml Code
- <Application android: name = ". MyApp" android: icon = "@ drawable/icon" android: label = "@ string/app_name">
- <Activity android: name = ". ClickableListItemActivity"
- Android: label = "@ string/app_name">
- <Intent-filter>
- <Action android: name = "android. intent. action. MAIN"/>
- <Category android: name = "android. intent. category. LAUNCHER"/>
- </Intent-filter>
- </Activity>
- </Application>
Note: