保存在Application类中的静态上下文并在Singleton Toast构建器中使用,这是否会造成内存泄漏? [英] Static context saved in Application class and used in a singleton toast builder, does this create a memory leak?

查看:254
本文介绍了保存在Application类中的静态上下文并在Singleton Toast构建器中使用,这是否会造成内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单例的Toast展示类,它可以跟踪当前的Toast,并在再次启动时将其取消:

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;
    }
}

(此示例的扩展说明可在以下位置找到: Android中的烤面包问题)

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

链接中的答案与这段代码之间的主要区别是上下文,它不作为参数传递.我使用保存在App类中的静态上下文来获取它,该上下文在应用程序启动时保存:

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?

推荐答案

第一个 不,如上所述,如果仅在应用程序中保存上下文,则不会导致内存泄漏.

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.

这篇关于保存在Application类中的静态上下文并在Singleton Toast构建器中使用,这是否会造成内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆