I have an abstract BaseFragmentActivity class that extends to all my actions in my Android app. In this class, I keep a static link to the current activity as sCurrentActivity . In my onStart() I set this as follows:
public abstract class BaseFragmentActivity extends FragmentActivity { private static BaseFragmentActivity sCurrentActivity; public static BaseFragmentActivity getCurrentActivity(){ return sCurrentActivity; } @Override protected void onStart() { super.onStart(); sCurrentActivity = this; }
Using this, from anywhere in the code I can get the current activity / context by calling:
BaseFragmentActivity.getCurrentActivity()
So, everything that I read says that I should not put links to actions / contexts. But if this static variable is distributed between all actions, do I really lose context every time I start a new action? I read a Romain Guy post about avoiding memory leaks ( http://android-developers.blogspot.co.uk/2009/01/avoiding-memory-leaks.html ), watched videos with performance characteristics on the Android developer channel, https: / /youtu.be/h7qHsk1nWKI and https://youtu.be/BkbHeFHn8JY ), and I'm reasonably sure this is bad practice. But can anyone help me understand the exact reason why and where this happens, if that happens. I want to make a case to remove this, but I need a stronger argument than "I think this is a context leak."
EDIT: For clarity, this is a code base that I inherited, where everything is very closely connected and disordered, this function is used almost everywhere where you need to look for a context object. Inside the Spells dialog, new intentions are activated, internal array adapters, even (for unknown reasons) inside fragments, to get views inside parent activity! I need to justify the refactoring efforts to our product owner on new features so that they understand.
K4KYA source share