Why don't you get the help from Application
class,
Read this > https://developer.android.com/reference/android/app/Application.html
Base class for maintaining global application state. You can provide
your own implementation by creating a subclass and specifying the
fully-qualified name of this subclass as the "android:name" attribute
in your AndroidManifest.xml's tag. The Application
class, or your subclass of the Application class, is instantiated
before any other class when the process for your application/package
is created.
Note: There is normally no need to subclass Application. In most
situations, static singletons can provide the same functionality in a
more modular way. If your singleton needs a global context (for
example to register broadcast receivers), include
Context.getApplicationContext() as a Context argument when invoking
your singleton's getInstance() method.
You can do that by keeping a Base class to maintain global application state,here in my example useed the Application object as a singleton object
public class MyApplication extends Application {
private static MyApplication singleton;
public static MyApplication getInstance() {
return singleton;
}
@Override
public void onCreate() {
super.onCreate();
singleton = this;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
public void onLowMemory() {
super.onLowMemory();
}
@Override
public void onTerminate() {
super.onTerminate();
}
}
In your AndroidManifest
specify that using android:name
under application tag
<application android:icon="@drawable/icon" android:label="@string/app_name" android:name="MyApplication">
Now you can access this anywhere like
MyApplication mApplication = (MyApplication)getApplicationContext();