Static context saved in Application class and used in a singleton toast builder, does this create a memory leak?

一世执手 提交于 2019-12-25 09:26:19

问题


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.



来源:https://stackoverflow.com/questions/40573279/static-context-saved-in-application-class-and-used-in-a-singleton-toast-builder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!