Is there a way to get the current Context
instance inside a static method?
I\'m looking for that way because I hate saving the \'Context\' instance eac
If you for some reason want Application context in any class, not just those extending application/activity, maybe for some factory or helper classes. You can add the following singleton to your app.
public class GlobalAppContextSingleton {
private static GlobalAppContextSingleton mInstance;
private Context context;
public static GlobalAppContextSingleton getInstance() {
if (mInstance == null) mInstance = getSync();
return mInstance;
}
private static synchronized GlobalAppContextSingleton getSync() {
if (mInstance == null) mInstance =
new GlobalAppContextSingleton();
return mInstance;
}
public void initialize(Context context) {
this.context = context;
}
public Context getApplicationContext() {
return context;
}
}
then initialize it in your application class's onCreate with
GlobalAppContextSingleton.getInstance().initialize(this);
use it anywhere by calling
GlobalAppContextSingleton.getInstance().getApplicationContext()
I don't recommend this approach to anything but application context however. As it can cause memory leaks.