You can use the Application class (an open class in the android.application package), that is:
The base class for those who need to maintain the global state of the application. You can provide your own implementation by specifying its name in your AndroidManifest.xml tag, which will call this class for you when the process is for your application / package.
To use this class, follow these steps:
public class App extends Application { private static Context mContext; public static Context getContext() { return mContext; } public static void setContext(Context mContext) { this.mContext = mContext; } ... }
In your manifest:
<application android:icon="..." android:label="..." android:name="com.example.yourmainpackagename.App" > class that extends Application ^^^
In action B:
public class B extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sampleactivitylayout); App.setContext(this); ... } ... }
In class A:
Context c = App.getContext();
Note :
Typically, there is no need for a subclass of Application. In most cases, static singlets can provide the same functionality in a more modular way. If your singleton needs a global context (for example, to register broadcast receivers), a function to get it can be provided with a Context that internally uses Context.getApplicationContext () when we first build a singleton.
hasanghaforian Sep 07 '12 at 15:45 2012-09-07 15:45
source share