简体   繁体   中英

Android: avoiding passing activity to singletons by storing inside the Application class = memory leak?

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.

  1. Completely avoid using activity context to a singleton object that.(yeah you know this)
  2. Dont inflate views, dialogs from app context. It will work but it will exclude styling and other stuff.

Then how?

  1. make utility methods with static methods, pass context as parameter.

  2. Use delegation (pass anonymous classes, or an interface)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM