Static context saved in Application class and used

2019-09-11 01:12发布

问题:

I've got a singleton Toast-showing class, which keeps track of the current toast and cancels it when it is started again:

public enum SingleToast {
    INSTANCE;

    private Toast currentToast;
    private String currentMessage;

    public void show(String message, int duration) {
        if (message.equals(currentMessage)) {
            currentToast.cancel();
        }

        currentToast = Toast.makeText(App.getContext(), message, duration);
        currentToast.show();

        currentMessage = message;
    }
}

(Extended explanation of this example can be found here: toast issue in android)

The main difference between the answer in the link and this piece of code is the context, which isn't passed as parameter. I get it using static context saved in the App class, which is saved at the startup of the app:

public class App extends Application {
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    public static Context getContext() {
        return context;
    }
}

I've read about this simple context solution in several blogs, and it helped a lot in retreiving context in classes for which passing context as parameters is just annoying, or even impossible.

However, I wonder if I am creating a memory leak!

First of all: does the static context by itself cause a memory leak (if yes, how can I prevent it without having to pass context always everywhere?)

Secondly: is it a problem to use context in a toast object, and save it as a field within a singleton, even if the context itself would not be static?

回答1:

First No, if you save context only in Application, as described above, it will not cause memory leak.

About second, It is almost the same to first case, but first is more simple in implementation than second.