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 the-the-do-is-to- create your own subclass of android.app.Application , and then specify this class in the application 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 from any context using the Context.getapplicationcontext () method (Activity also provides a method Getap Plication () 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 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).
Then add the app in 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>
Description
-
What you need to add: android:name= ". Your_app_name"
-
Location: Where the current activity is, (I just started thinking I need to create a new <application></application>)
android--Global variables very good, very powerful.