Reputation: 8021
I have a few singletons that require context information as they might have to show dialogs. Up until now I've passed the relevant contexts to the singletons, but this is increasingly leading to memory leaks. I was wondering whether storing a reference to the current activity inside the application class might be a way around this problem. Since the variable is overwritten everytime a new activity starts it shouldn't lead to a memory leak, but it's also accessible from all non-activity classes in the app.
Inside my application class:
private static Activity currentForegroundActivity;
public static void setCurrentlyVisibleActivity(Activity activity) {
currentForegroundActivity = activity;
}
public static Activity getCurrentlyVisibleActivity() {
return currentForegroundActivity;
}
Inside every activity:
@Override
public void onResume() {
super.onResume();
App.setCurrentlyVisibleActivity(this);
Inside every singleton:
methodThatRequiresUI(App.getCurrentlyVisibleActivity);
Are there any pitfalls going down this route that you can foresee? I suppose the application class might be cleared from memory by the OS, but if that happened the app itself would restart - it wouldn't lead to a null pointer. The get method might also get called during application startup before the set had been called - but I can write checks to get around that.
Upvotes: 0
Views: 735
Reputation: 3705
Then how?
make utility methods with static methods, pass context as parameter.
Use delegation (pass anonymous classes, or an interface)
Upvotes: 2